Arithmetic Operations to Check if All Digits of Given Number are Same

Another approach to check if all digits are the same in a given integer is by comparing each digit directly by using arithmetic operations, without converting the number to a string.

Example: Implementation of checking if all the digits of the given number are same in PHP using arithmetic operations.

PHP




<?php
// To check if all digits of given number are same
function areDigitsSame($number) {
    $lastDigit = $number % 10;
    while ($number > 0) {
        $currentDigit = $number % 10;
        if ($currentDigit != $lastDigit) {
            return false;
        }
        $number = (int)($number / 10);
    }
    return true;
}
  
// Given Data
$number = 2222;
  
if (areDigitsSame($number)) {
    echo "All digits of $number are same.";
} else {
    echo "All digits of $number are not same.";
}
?>


Output

All digits of 2222 are same.

Time Complexity: O(d), where d is the number of digits in the given number.
Auxiliary Space: O(1)

How to Check if All Digits of Given Number are Same in PHP ?

Given a number, our task is to check if all the digits of a given number are the same. This can be useful in various scenarios, such as validating user input or processing numerical data. In this article, we will explore different approaches to check if a given number’s digits are the same in PHP.

Examples:

Input: 1111
Output: All digits of 1111 are same

Input: 12345
Output: All digits of 12345 are not same

Table of Content

  • Using String Manipulation
  • Using Arithmetic Operations
  • Using String Functions

Similar Reads

String Manipulation to Check if All Digits of Given Number are Same

One way to check if all digits are the same in a given integer is by first converting the number to a string. Then compare each characters of this string with the first one and return true if all the characters are same, otherwise false....

Arithmetic Operations to Check if All Digits of Given Number are Same

...

String Functions to Check if All Digits of Given Number are Same

Another approach to check if all digits are the same in a given integer is by comparing each digit directly by using arithmetic operations, without converting the number to a string....

Contact Us