Count pairs in array such that one element is reverse of another | C ++ program to count the pairs in array such that one element is reverse of another ; Function to reverse the digits of the number ; Loop to iterate till the number is greater than 0 ; Extract the last digit and keep multiplying it by 10 to get the reverse of the number ; Function to find the pairs from the array such that one number is reverse of the other ; Iterate over every element in the array and increase the frequency of the element in hash map ; Iterate over every element in the array ; remove the current element from the hash map by decreasing the frequency to avoid counting when the number is a palindrome or when we visit its reverse ; Increment the count by the frequency of reverse of the number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int reverse ( int num ) { int rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = num / 10 ; } return rev_num ; } int countReverse ( int arr [ ] , int n ) { unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; ++ i ) ++ freq [ arr [ i ] ] ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { -- freq [ arr [ i ] ] ; res += freq [ reverse ( arr [ i ] ) ] ; } return res ; } int main ( ) { int a [ ] = { 16 , 61 , 12 , 21 , 25 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countReverse ( a , n ) << ' ' ; return 0 ; }