Largest even digit number not greater than N | function to return the largest number with all digits even ; convert the number to a string for easy operations ; find first odd digit ; if no digit , then N is the answer ; till first odd digit , add all even numbers ; decrease 1 from the odd digit ; add 0 in the rest of the digits ; Driver Code
< ? php function largestNumber ( $ n ) { $ s = " " ; $ duplicate = $ n ; while ( $ n ) { $ s = chr ( $ n % 10 + 48 ) . $ s ; $ n = ( int ) ( $ n / 10 ) ; } $ index = -1 ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) { if ( ord ( $ s [ $ i ] - '0' ) % 2 & 1 ) { $ index = $ i ; break ; } } if ( $ index == -1 ) return $ duplicate ; $ num = 0 ; for ( $ i = 0 ; $ i < $ index ; $ i ++ ) $ num = $ num * 10 + ( ord ( $ s [ $ i ] ) - ord ( '0' ) ) ; $ num = $ num * 10 + ( ( ord ( $ s [ $ i ] ) - ord ( '0' ) ) - 1 ) ; for ( $ i = $ index + 1 ; $ i < strlen ( $ s ) ; $ i ++ ) $ num = $ num * 10 + 8 ; return $ num ; } $ N = 24578 ; echo largestNumber ( $ N ) ; ? >