Count pairs in array such that one element is reverse of another | Java 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
import java . util . * ; class GFG { public static int reverse ( int num ) { int rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = num / 10 ; } return rev_num ; } public static int countReverse ( int arr [ ] , int n ) { HashMap < Integer , Integer > freq = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( freq . containsKey ( arr [ i ] ) ) { freq . replace ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . put ( arr [ i ] , 1 ) ; } } int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . containsKey ( arr [ i ] ) ) { freq . replace ( arr [ i ] , freq . get ( arr [ i ] ) - 1 ) ; } else { freq . put ( arr [ i ] , - 1 ) ; } if ( freq . containsKey ( reverse ( arr [ i ] ) ) ) { res += freq . get ( reverse ( arr [ i ] ) ) ; } } return res ; } public static void main ( String [ ] args ) { int a [ ] = { 16 , 61 , 12 , 21 , 25 } ; int n = a . length ; System . out . println ( countReverse ( a , n ) ) ; } }