Smallest even digits number not less than N | CPP program to print the smallest integer not less than N with all even digits ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int trickyCase ( string s , int index ) { int index1 = -1 ; for ( int i = index - 1 ; i >= 0 ; i -- ) { int digit = s [ i ] - '0' ; if ( digit != 8 ) { index1 = i ; break ; } } if ( index1 == -1 ) return 2 * pow ( 10 , s . length ( ) ) ; int num = 0 ; for ( int 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 ( int i = index1 + 1 ; i < s . length ( ) ; i ++ ) num = num * 10 ; return num ; } int smallestNumber ( int n ) { int num = 0 ; 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 ++ ) { int 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 ( 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 ; return num ; } int main ( ) { int N = 2397 ; cout << smallestNumber ( N ) ; return 0 ; }