text: Largest palindromic number by permuting digits | JAVA 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: import java . util . * ; class GFG { static boolean possibility ( HashMap < Integer , Integer > m , int length , String s ) { int countodd = 0 ; for ( int i = 0 ; i < length ; i ++ ) { if ( m . get ( s . charAt ( i ) - '0' ) % 2 == 1 ) countodd ++ ; if ( countodd > 1 ) return false ; } return true ; } static void largestPalindrome ( String s ) { int l = s . length ( ) ; HashMap < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < l ; i ++ ) if ( m . containsKey ( s . charAt ( i ) - '0' ) ) m . put ( s . charAt ( i ) - '0' , m . get ( s . charAt ( i ) - '0' ) + 1 ) ; else m . put ( s . charAt ( i ) - '0' , 1 ) ; if ( possibility ( m , l , s ) == false ) { System . out . print ( " Palindrome ▁ cannot ▁ be ▁ formed " ) ; return ; } char [ ] largest = new char [ l ] ; int front = 0 ; for ( int i = 9 ; i >= 0 ; i -- ) { if ( m . containsKey ( i ) && m . get ( i ) % 2 == 1 ) { largest [ l / 2 ] = ( char ) ( i + 48 ) ; m . put ( i , m . get ( i ) - 1 ) ; while ( m . get ( i ) > 0 ) { largest [ front ] = ( char ) ( i + 48 ) ; largest [ l - front - 1 ] = ( char ) ( i + 48 ) ; m . put ( i , m . get ( i ) - 2 ) ; front ++ ; } } else { while ( m . containsKey ( i ) && m . get ( i ) > 0 ) { largest [ front ] = ( char ) ( i + 48 ) ; largest [ l - front - 1 ] = ( char ) ( i + 48 ) ; m . put ( i , m . get ( i ) - 2 ) ; front ++ ; } } } for ( int i = 0 ; i < l ; i ++ ) System . out . print ( largest [ i ] ) ; } public static void main ( String [ ] args ) { String s = "313551" ; largestPalindrome ( s ) ; } }