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
< ? php function reverse ( & $ num , $ i , $ j ) { while ( $ i < $ j ) { $ t = $ num [ $ i ] ; $ num [ $ i ] = $ num [ $ j ] ; $ num [ $ j ] = $ t ; $ i ++ ; $ j -- ; } } function nextPalin ( $ num , $ n ) { if ( $ n <= 3 ) { echo " Not ▁ Possible " ; return ; } $ mid = ( $ n / 2 ) - 1 ; $ i = $ mid - 1 ; $ j ; for ( ; $ i >= 0 ; $ i -- ) if ( $ num [ $ i ] < $ num [ $ i + 1 ] ) break ; if ( $ i < 0 ) { echo " Not ▁ Possible " ; return ; } $ smallest = $ i + 1 ; $ j = 0 ; for ( $ j = $ i + 2 ; $ j <= $ mid ; $ j ++ ) if ( $ num [ $ j ] > $ num [ $ i ] && $ num [ $ j ] < $ num [ $ smallest ] ) $ smallest = $ j ; $ t = $ num [ $ i ] ; $ num [ $ i ] = $ num [ $ smallest ] ; $ num [ $ smallest ] = $ t ; $ t = $ num [ $ n - $ i - 1 ] ; $ num [ $ n - $ i - 1 ] = $ num [ $ n - $ smallest - 1 ] ; $ num [ $ n - $ smallest - 1 ] = $ t ; reverse ( $ num , $ i + 1 , $ mid ) ; if ( $ n % 2 == 0 ) reverse ( $ num , $ mid + 1 , $ n - $ i - 2 ) ; else reverse ( $ num , $ mid + 2 , $ n - $ i - 2 ) ; echo " Next ▁ Palindrome : ▁ " . $ num ; } $ num = "4697557964" ; $ n = strlen ( $ num ) ; nextPalin ( $ num , $ n ) ; ? >