Largest even digit number not greater than N | CPP program to print the largest integer not greater than N with all even digits ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNumber ( int n ) { string s = " " ; int duplicate = n ; while ( n ) { s = char ( n % 10 + 48 ) + s ; n /= 10 ; } int index = -1 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ( s [ i ] - '0' ) % 2 & 1 ) { index = i ; break ; } } if ( index == -1 ) return duplicate ; int num = 0 ; for ( int i = 0 ; i < index ; i ++ ) num = num * 10 + ( s [ i ] - '0' ) ; num = num * 10 + ( s [ index ] - '0' - 1 ) ; for ( int i = index + 1 ; i < s . length ( ) ; i ++ ) num = num * 10 + 8 ; return num ; } int main ( ) { int N = 24578 ; cout << largestNumber ( N ) ; return 0 ; }