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 ) { // Converting the number into a string // and splitting this string into an array of digits $digits = str_split ((string) $number ); // Counting the occurrences of each digit $counts = array_count_values ( $digits ); // Filtering out counts where the digit occurs only once // to find the repeating digits only $repeatingCounts = array_filter ( $counts , function ( $count ) { return $count > 1; }); return $repeatingCounts ; } $num = 1234567654321; $repeatingCounts = countRepeatingDigits( $num ); // Iterating through the results and printing them foreach ( $repeatingCounts as $digit => $count ) { echo "Digit $digit repeats $count times\n" ; } ?> |
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)
How to Count of Repeating Digits in a Given Number in PHP ?
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.
Table of Content
- Using String Manipulation and Arrays
- Using Arithmetic Operations
Contact Us