Count pairs in an array which have at least one digit common | CPP Program to count pairs in an array with some common digit ; Returns true if the pair is valid , otherwise false ; converting integers to strings ; Iterate over the strings and check if a character in first string is also present in second string , return true ; No common digit found ; Returns the number of valid pairs ; Iterate over all possible pairs ; Driver Code to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkValidPair ( int num1 , int num2 ) { string s1 = to_string ( num1 ) ; string s2 = to_string ( num2 ) ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) for ( int j = 0 ; j < s2 . size ( ) ; j ++ ) if ( s1 [ i ] == s2 [ j ] ) return true ; return false ; } int countPairs ( int arr [ ] , int n ) { int numberOfPairs = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( checkValidPair ( arr [ i ] , arr [ j ] ) ) numberOfPairs ++ ; return numberOfPairs ; } int main ( ) { int arr [ ] = { 10 , 12 , 24 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) << endl ; return 0 ; }