Count pairs in an array having sum of elements with their respective sum of digits equal | package whatever do not write package name here ; Function to find the sum of digits of the number N ; Stores the sum of digits ; If the number N is greater than 0 ; Return the sum ; Function to find the count of pairs such that arr [ i ] + sumOfDigits ( arr [ i ] ) is equal to ( arr [ j ] + sumOfDigits ( arr [ j ] ) ; Stores the frequency of value of arr [ i ] + sumOfDigits ( arr [ i ] ) ; Traverse the given array ; Find the value ; Increment the frequency ; Stores the total count of pairs ; Traverse the map mp ; Update the count of pairs ; Return the total count of pairs ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static int sumOfDigits ( int N ) { int sum = 0 ; while ( N > 0 ) { sum += ( N % 10 ) ; N = N / 10 ; } return sum ; } static int CountPair ( int arr [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int val = arr [ i ] + sumOfDigits ( arr [ i ] ) ; if ( mp . containsKey ( val ) ) { mp . put ( val , mp . get ( val ) + 1 ) ; } else { mp . put ( val , 1 ) ; } } int count = 0 ; for ( Map . Entry < Integer , Integer > x : mp . entrySet ( ) ) { int val = x . getKey ( ) ; int times = x . getValue ( ) ; count += ( ( times * ( times - 1 ) ) / 2 ) ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 105 , 96 , 20 , 2 , 87 , 96 } ; int N = 6 ; System . out . println ( CountPair ( arr , N ) ) ; } }