Largest number not greater than N all the digits of which are odd | function to return the largest number with all digits odd ; convert the number to a string for easy operations ; find first even digit ; if no even digit , then N is the answer ; till first even digit , add all odd numbers ; decrease 1 from the even digit ; add 9 in the rest of the digits ; Driver Code
function largestNumber ( n ) { var s = " " ; var duplicate = n ; while ( n > 0 ) { s = String . fromCharCode ( n % 10 + 48 ) + s ; n = parseInt ( n / 10 ) ; } var index = - 1 ; for ( i = 0 ; i < s . length ; i ++ ) { if ( ( ( s . charAt ( i ) . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) % 2 & 1 ) == 0 ) { index = i ; break ; } } if ( index == - 1 ) return duplicate ; var num = 0 ; for ( i = 0 ; i < index ; i ++ ) num = num * 10 + ( s . charAt ( i ) . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ; num = num * 10 + ( s . charAt ( index ) . charCodeAt ( 0 ) - ( ' ' ) . charCodeAt ( 0 ) - 1 ) ; for ( i = index + 1 ; i < s . length ; i ++ ) num = num * 10 + 9 ; return num ; } var N = 24578 ; document . write ( largestNumber ( N ) ) ;