Largest number not greater than N all the digits of which are odd | Java program to print the largest integer not greater than N with all odd digits ; 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
class GFG { static int largestNumber ( int n ) { String s = " " ; int duplicate = n ; while ( n > 0 ) { s = ( char ) ( n % 10 + 48 ) + s ; n /= 10 ; } int index = - 1 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ( ( int ) ( s . charAt ( i ) - '0' ) % 2 & 1 ) == 0 ) { index = i ; break ; } } if ( index == - 1 ) return duplicate ; int num = 0 ; for ( int i = 0 ; i < index ; i ++ ) num = num * 10 + ( int ) ( s . charAt ( i ) - '0' ) ; num = num * 10 + ( ( int ) s . charAt ( index ) - ( int ) ( '0' ) - 1 ) ; for ( int i = index + 1 ; i < s . length ( ) ; i ++ ) num = num * 10 + 9 ; return num ; } public static void main ( String [ ] args ) { int N = 24578 ; System . out . println ( largestNumber ( N ) ) ; } }