How to Count of Repeating Digits in a Given Number in PHP ?
Last Updated :
27 Feb, 2024
Counting the number of repeating digits in a given number is a common task in programming. This can be useful in various scenarios, such as data analysis or validation. In this article, we will explore different approaches to count the repeating digits in a given number using PHP.
Count of Repeating Digits using String Manipulation and Arrays
One way to count repeating digits is by converting the number to a string, splitting it into an array of digits, and then use array_count_values()
function to count the occurrences of each digit. Finally, the array_filter()
function is used to filter out digits that occur only once, leaving only the repeating digits.
Example: Illustration of counting the number of repeating digits in a given number in PHP using string manipulation and arrays.
PHP
<?php
function countRepeatingDigits( $number ) {
$digits = str_split ((string) $number );
$counts = array_count_values ( $digits );
$repeatingCounts = array_filter ( $counts , function ( $count ) {
return $count > 1;
});
return $repeatingCounts ;
}
$num = 1234567654321;
$repeatingCounts = countRepeatingDigits( $num );
foreach ( $repeatingCounts as $digit => $count ) {
echo "Digit $digit repeats $count times\n" ;
}
?>
|
Output
Digit 1 repeats 2 times
Digit 2 repeats 2 times
Digit 3 repeats 2 times
Digit 4 repeats 2 times
Digit 5 repeats 2 times
Digit 6 repeats 2 times
Time Complexity: O(1)
Auxiliary Space: O(1)
Count of Repeating Digits using Arithmetic Operations
Another approach is to use arithmetic operations to extract each digit of the number and count their occurrences. Finally, filter out those digits that occur only once, leaving only the repeating digits.
Example: Illustration of counting the number of repeating digits in a given number in PHP using arithmetic operations.
PHP
<?php
function countRepeatingDigits( $number ) {
$counts = [];
while ( $number > 0) {
$digit = $number % 10;
$number = (int)( $number / 10);
if (!isset( $counts [ $digit ])) {
$counts [ $digit ] = 0;
}
$counts [ $digit ]++;
}
$repeatingCounts = array_filter ( $counts , function ( $count ) {
return $count > 1;
});
return $repeatingCounts ;
}
$num = 1234567654321;
$repeatingCounts = countRepeatingDigits( $num );
foreach ( $repeatingCounts as $digit => $count ) {
echo "Digit $digit repeats $count times\n" ;
}
?>
|
Output
Digit 1 repeats 2 times
Digit 2 repeats 2 times
Digit 3 repeats 2 times
Digit 4 repeats 2 times
Digit 5 repeats 2 times
Digit 6 repeats 2 times
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...