Smallest even digits number not less than N | function to return the answer when the first odd digit is 9 ; traverse towwars the left to find the non - 8 digit ; index digit ; if digit is not 8 , then break ; if on the left side of the '9' , no 8 is found then we return by adding a 2 and 0 's ; till non - 8 digit add all numbers ; if non - 8 is even or odd than add the next even . ; add 0 to right of 9 ; function to return the smallest number with all digits even ; convert the number to string to perform operations ; find out the first odd number ; if no odd numbers are there , than n is the answer ; if the odd number is 9 , than tricky case handles it ; add all digits till first odd ; increase the odd digit by 1 ; add 0 to the right of the odd number ; Driver Code
< ? php function trickyCase ( $ s , $ index ) { $ index1 = -1 ; for ( $ i = $ index - 1 ; $ i >= 0 ; $ i -- ) { $ digit = $ s [ $ i ] - '0' ; if ( $ digit != 8 ) { $ index1 = $ i ; break ; } } if ( $ index1 == -1 ) return 2 * pow ( 10 , strlen ( $ s ) ) ; $ num = 0 ; for ( $ i = 0 ; $ i < $ index1 ; $ i ++ ) $ num = $ num * 10 + ( $ s [ $ i ] - '0' ) ; if ( $ s [ $ index1 ] % 2 == 0 ) $ num = $ num * 10 + ( $ s [ $ index1 ] - '0' + 2 ) ; else $ num = $ num * 10 + ( $ s [ $ index1 ] - '0' + 1 ) ; for ( $ i = $ index1 + 1 ; $ i < strlen ( $ s ) ; $ i ++ ) $ num = $ num * 10 ; return $ num ; } function smallestNumber ( $ n ) { $ num = 0 ; $ s = " " ; $ duplicate = $ n ; while ( $ n ) { $ s = chr ( $ n % 10 + 48 ) . $ s ; $ n = ( int ) ( $ n / 10 ) ; } $ index = -1 ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) { $ digit = $ s [ $ i ] - '0' ; if ( $ digit & 1 ) { $ index = $ i ; break ; } } if ( $ index == -1 ) return $ duplicate ; if ( $ s [ $ index ] == '9' ) { $ num = trickyCase ( $ s , $ index ) ; return $ num ; } for ( $ i = 0 ; $ i < $ index ; $ i ++ ) $ num = $ num * 10 + ( $ s [ $ i ] - '0' ) ; $ num = $ num * 10 + ( $ s [ $ index ] - '0' + 1 ) ; for ( $ i = $ index + 1 ; $ i < strlen ( $ s ) ; $ i ++ ) $ num = $ num * 10 ; return $ num ; } $ N = 2397 ; echo smallestNumber ( $ N ) ; ? >