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 = []; // Loop through each digit in the given number while ( $number > 0) { // Extract the last digit $digit = $number % 10; // Remove the last digit from the number $number = (int)( $number / 10); // If the digit is not in the counts array // initialize its count to 0 if (!isset( $counts [ $digit ])) { $counts [ $digit ] = 0; } $counts [ $digit ]++; } // Filter out counts where the digit occurs only once $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" ; } ?> |
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