Rearrangement of a number which is also divisible by it | CPP program for finding rearrangement of n that is divisible by n ; perform hashing for given n ; perform hashing ; check whether any arrangement exists ; Create a hash for given number n The hash is of size 10 and stores count of each digit in n . ; check for all possible multipliers ; check hash table for both . Please refer below link for help of equal ( ) https : www . geeksforgeeks . org / stdequal - in - cpp / ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void storeDigitCounts ( int n , vector < int > & hash ) { while ( n ) { hash [ n % 10 ] ++ ; n /= 10 ; } } int rearrange ( int n ) { vector < int > hash_n ( 10 , 0 ) ; storeDigitCounts ( n , hash_n ) ; for ( int mult = 2 ; mult < 10 ; mult ++ ) { int curr = n * mult ; vector < int > hash_curr ( 10 , 0 ) ; storeDigitCounts ( curr , hash_curr ) ; if ( equal ( hash_n . begin ( ) , hash_n . end ( ) , hash_curr . begin ( ) ) ) return curr ; } return -1 ; } int main ( ) { int n = 10035 ; cout << rearrange ( n ) ; return 0 ; }