text: Largest palindromic number by permuting digits | CPP program to print the largest palindromic number by permuting digits of a number ; function to check if a number can be permuted to form a palindrome number ; counts the occurrence of number which is odd ; if occurrence is odd ; if number exceeds 1 ; function to print the largest palindromic number by permuting digits of a number ; string length ; map that marks the occurrence of a number ; check the possibility of a palindromic number ; string array that stores the largest permuted palindromic number ; pointer of front ; greedily start from 9 to 0 and place the greater number in front and odd in the middle ; if the occurrence of number is odd ; place one odd occurring number in the middle ; decrease the count ; place the rest of numbers greedily ; if all numbers occur even times , then place greedily ; place greedily at front ; 2 numbers are placed , so decrease the count ; increase placing position ; print the largest string thus formed ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool possibility ( unordered_map < int , int > m , int length , string s ) { int countodd = 0 ; for ( int i = 0 ; i < length ; i ++ ) { if ( m [ s [ i ] - '0' ] & 1 ) countodd ++ ; if ( countodd > 1 ) return false ; } return true ; } void largestPalindrome ( string s ) { int l = s . length ( ) ; unordered_map < int , int > m ; for ( int i = 0 ; i < l ; i ++ ) m [ s [ i ] - '0' ] ++ ; if ( possibility ( m , l , s ) == false ) { cout << " Palindrome ▁ cannot ▁ be ▁ formed " ; return ; } char largest [ l ] ; int front = 0 ; for ( int i = 9 ; i >= 0 ; i -- ) { if ( m [ i ] & 1 ) { largest [ l / 2 ] = char ( i + 48 ) ; m [ i ] -- ; while ( m [ i ] > 0 ) { largest [ front ] = char ( i + 48 ) ; largest [ l - front - 1 ] = char ( i + 48 ) ; m [ i ] -= 2 ; front ++ ; } } else { while ( m [ i ] > 0 ) { largest [ front ] = char ( i + 48 ) ; largest [ l - front - 1 ] = char ( i + 48 ) ; m [ i ] -= 2 ; front ++ ; } } } for ( int i = 0 ; i < l ; i ++ ) cout << largest [ i ] ; } int main ( ) { string s = "313551" ; largestPalindrome ( s ) ; return 0 ; }