Find the most frequent digit without using array / string | Finds maximum occurring digit without using any array / string ; Simple function to count occurrences of digit d in x ; int count = 0 ; Initialize count of digit d ; Increment count if current digit is same as d ; Returns the max occurring digit in x ; Handle negative number ; Traverse through all digits ; Count occurrences of current digit ; Update max_count and result if needed ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOccurrences ( long int x , int d ) { while ( x ) { if ( x % 10 == d ) count ++ ; x = x / 10 ; } return count ; } int maxOccurring ( long int x ) { if ( x < 0 ) x = - x ; for ( int d = 0 ; d <= 9 ; d ++ ) { int count = countOccurrences ( x , d ) ; if ( count >= max_count ) { max_count = count ; result = d ; } } return result ; } int main ( ) { long int x = 1223355 ; cout << " Max ▁ occurring ▁ digit ▁ is ▁ " << maxOccurring ( x ) ; return 0 ; }