Next higher palindromic number using the same set of digits | Function to reverse the digits in the range i to j in ' num ' ; Function to find next higher palindromic number using the same set of digits ; If length of number is less than '3' then no higher palindromic number can be formed ; Find the index of last digit in the 1 st half of ' num ' ; Start from the ( mid - 1 ) th digit and find the first digit that is smaller than the digit next to it . ; If no such digit is found , then all digits are in descending order which means there cannot be a greater palindromic number with same set of digits ; Find the smallest digit on right side of ith digit which is greater than num [ i ] up to index ' mid ' ; Swap num [ i ] with num [ smallest ] ; As the number is a palindrome , the same swap of digits should be performed in the 2 nd half of ' num ' ; Reverse digits in the range ( i + 1 ) to mid ; If n is even , then reverse digits in the range mid + 1 to n - i - 2 ; Else if n is odd , then reverse digits in the range mid + 2 to n - i - 2 ; Required next higher palindromic number ; Driver Code
function reverse ( num , i , j ) { while ( i < j ) { var temp = num [ i ] ; num [ i ] = num [ j ] ; num [ j ] = temp ; i ++ ; j -- ; } } function nextPalin ( num , n ) { if ( n <= 3 ) { document . write ( " " ) ; return ; } var temp ; var mid = n / 2 - 1 ; var i , j ; for ( i = mid - 1 ; i >= 0 ; i -- ) if ( num [ i ] < num [ i + 1 ] ) break ; if ( i < 0 ) { document . write ( " " ) ; return ; } var smallest = i + 1 ; for ( j = i + 2 ; j <= mid ; j ++ ) if ( num [ j ] > num [ i ] && num [ j ] <= num [ smallest ] ) smallest = j ; temp = num [ i ] ; num [ i ] = num [ smallest ] ; num [ smallest ] = temp ; temp = num [ n - i - 1 ] ; num [ n - i - 1 ] = num [ n - smallest - 1 ] ; num [ n - smallest - 1 ] = temp ; reverse ( num , i + 1 , mid ) ; if ( n % 2 == 0 ) reverse ( num , mid + 1 , n - i - 2 ) ; else reverse ( num , mid + 2 , n - i - 2 ) ; var result = num . join ( ' ' ) ; document . write ( " " + result ) ; } var str = " " ; var num = str . split ( ' ' ) ; var n = str . length ; nextPalin ( num , n ) ;