Number of common digits present in two given numbers | C ++ program for the above approach ; Function to count number of digits that are common in both N and M ; Stores the count of common digits ; Stores the count of digits of N ; Stores the count of digits of M ; Iterate over the digits of N ; Increment the count of last digit of N ; Update N ; Iterate over the digits of M ; Increment the count of last digit of M ; Update M ; Iterate over the range [ 0 , 9 ] ; If freq1 [ i ] and freq2 [ i ] both exceeds 0 ; Increment count by 1 ; Return the count ; Driver Code ; Input
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CommonDigits ( int N , int M ) { int count = 0 ; int freq1 [ 10 ] = { 0 } ; int freq2 [ 10 ] = { 0 } ; while ( N > 0 ) { freq1 [ N % 10 ] ++ ; N = N / 10 ; } while ( M > 0 ) { freq2 [ M % 10 ] ++ ; M = M / 10 ; } for ( int i = 0 ; i < 10 ; i ++ ) { if ( freq1 [ i ] > 0 & freq2 [ i ] > 0 ) { count ++ ; } } return count ; } int main ( ) { int N = 748294 ; int M = 34298156 ; cout << CommonDigits ( N , M ) ; return 0 ; }