Smallest even digits number not less than N
Last Updated :
16 Dec, 2022
Given a number N, we need to write a program to find the smallest number not less than N, which has all digits even.
Examples:
Input: N = 1345
Output: 2000
Explanation: 2000 is the smallest number not less than N, whose all digits are even.
Input : N = 2397
Output : 2400
Explanation: 2400 is the smallest number not less than N, whose all digits are even.
Naive approach: A naive approach is to keep iterating from N until we find a number with all digits even.
Below is the implementation of above approach:
C++
// CPP program to print the smallest
// integer not less than N with all even digits
#include <bits/stdc++.h>
using namespace std;
// function to check if all digits
// are even of a given number
int check_digits(int n)
{
// iterate for all digits
while (n) {
if ((n % 10) % 2) // if digit is odd
return 0;
n /= 10;
}
// all digits are even
return 1;
}
// function to return the smallest number
// with all digits even
int smallest_number(int n)
{
// iterate till we find a
// number with all digits even
for (int i = n;; i++)
if (check_digits(i))
return i;
}
// Driver Code
int main()
{
int N = 2397;
cout << smallest_number(N);
return 0;
}
Java
// Java program to print the smallest
// integer not less than N with all
// even digits
import java.io.*;
public class GFG {
// function to check if all digits
// are even of a given number
static int check_digits(int n)
{
// iterate for all digits
while (n != 0) {
// if digit is odd
if ((n % 10) % 2 != 0)
return 0;
n /= 10;
}
// all digits are even
return 1;
}
// function to return the smallest
// number with all digits even
static int smallest_number(int n)
{
// iterate till we find a
// number with all digits even
for (int i = n; ; i++)
if (check_digits(i) != 0)
return i;
}
// Driver Code
public static void main(String[] args)
{
int N = 2397;
System.out.println(smallest_number(N));
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python3
# Python3 program to print the smallest
# integer not less than N with
# all even digits
# function to check if all digits
# are even of a given number
def check_digits(n) :
# iterate for all digits
while (n) :
# if digit is odd
if ((n % 10) % 2) :
return 0
n = int(n / 10)
# all digits are even
return 1
# function to return the
# smallest number with
# all digits even
def smallest_number(n) :
# iterate till we find a
# number with all digits even
for i in range(n, 2401) :
if (check_digits(i) == 1) :
return (i)
# Driver Code
N = 2397
print (str(smallest_number(N)))
# This code is contributed by
# Manish Shaw (manishshaw1)
C#
// C# program to print the smallest
// integer not less than N with all
// even digits
using System;
class GFG {
// function to check if all digits
// are even of a given number
static int check_digits(int n)
{
// iterate for all digits
while (n != 0) {
// if digit is odd
if ((n % 10) % 2 != 0)
return 0;
n /= 10;
}
// all digits are even
return 1;
}
// function to return the smallest
// number with all digits even
static int smallest_number(int n)
{
// iterate till we find a
// number with all digits even
for (int i = n; ; i++)
if (check_digits(i) != 0)
return i;
}
// Driver Code
public static void Main()
{
int N = 2397;
Console.WriteLine(smallest_number(N));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to print the smallest
// integer not less than N with
// all even digits
// function to check if all digits
// are even of a given number
function check_digits($n)
{
// iterate for all digits
while ($n)
{
// if digit is odd
if (($n % 10) % 2)
return 0;
$n /= 10;
}
// all digits are even
return 1;
}
// function to return the
// smallest number with
// all digits even
function smallest_number( $n)
{
// iterate till we find a
// number with all digits even
for ($i = $n; ; $i++)
if (check_digits($i))
return $i;
}
// Driver Code
$N = 2397;
echo smallest_number($N);
// This code is contributed by m_kit
?>
JavaScript
<script>
// Javascript program to print the smallest
// integer not less than N with all
// even digits
// function to check if all digits
// are even of a given number
function check_digits(n)
{
// iterate for all digits
while (n != 0) {
// if digit is odd
if ((n % 10) % 2 != 0)
return 0;
n = parseInt(n/10);
}
// all digits are even
return 1;
}
// function to return the smallest
// number with all digits even
function smallest_number(n)
{
// iterate till we find a
// number with all digits even
for (i = n; ; i++)
if (check_digits(i) != 0)
return i;
}
// Driver Code
var N = 2397;
document.write(smallest_number(N));
// This code is contributed by 29AjayKumar
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: We can find the number by increasing the first odd digit in N by one and replacing all digits to the right of that odd digit with the smallest even digit (i.e. 0). If there are no odd digits in N, then N is the smallest number itself. For example, consider N = 213. Increment first odd digit in N i.e., 1 to 2 and replace all digits right to it by 0. So, our required number will be 220.
Tricky Cases:
- If the first odd digit in N is 9, then we must replace the digit immediately to the left of that odd digit with the next even digit. For example, if N=44934, then smallest number=46000.
- Another tricky case is when the first odd digit is 9 and the digit directly to the left of the first odd digit is 8. In this case, we must replace the digit directly to the left of first odd digit by 0 and the digit left to this digit by next even digit, and keep doing this until we find a digit other than 8. For example, if N=86891, then Y=88000. Finally, if all digits to the left continue to be 8 until we reach the leftmost digit, or if the first digit of N is 9, then we must add the smallest non-zero even digit (i.e. 2) as a new digit on the left. For example, if N=891 or N=910, then Y=2000.
Below is the implementation of the efficient approach:
C++
// CPP program to print the smallest
// integer not less than N with all even digits
#include <bits/stdc++.h>
using namespace std;
// function to return the answer when the
// first odd digit is 9
int trickyCase(string s, int index)
{
int index1 = -1;
// traverse towards the left to find the non-8 digit
for (int i = index - 1; i >= 0; i--) {
// index digit
int digit = s[i] - '0';
// if digit is not 8, then break
if (digit != 8) {
index1 = i;
break;
}
}
// if on the left side of the '9', no 8
// is found then we return by adding a 2 and 0's
if (index1 == -1)
return 2 * pow(10, s.length());
int num = 0;
// till non-8 digit add all numbers
for (int i = 0; i < index1; i++)
num = num * 10 + (s[i] - '0');
// if non-8 is even or odd than add the next even.
if (s[index1] % 2 == 0)
num = num * 10 + (s[index1] - '0' + 2);
else
num = num * 10 + (s[index1] - '0' + 1);
// add 0 to right of 9
for (int i = index1 + 1; i < s.length(); i++)
num = num * 10;
return num;
}
// function to return the smallest number
// with all digits even
int smallestNumber(int n)
{
int num = 0;
string s = "";
int duplicate = n;
// convert the number to string to
// perform operations
while (n) {
s = char(n % 10 + 48) + s;
n /= 10;
}
int index = -1;
// find out the first odd number
for (int i = 0; i < s.length(); i++) {
int digit = s[i] - '0';
if (digit & 1) {
index = i;
break;
}
}
// if no odd numbers are there, than n is the answer
if (index == -1)
return duplicate;
// if the odd number is 9,
// than tricky case handles it
if (s[index] == '9') {
num = trickyCase(s, index);
return num;
}
// add all digits till first odd
for (int i = 0; i < index; i++)
num = num * 10 + (s[i] - '0');
// increase the odd digit by 1
num = num * 10 + (s[index] - '0' + 1);
// add 0 to the right of the odd number
for (int i = index + 1; i < s.length(); i++)
num = num * 10;
return num;
}
// Driver Code
int main()
{
int N = 2397;
cout << smallestNumber(N);
return 0;
}
Java
// Java program to print the
// smallest integer not less
// than N with all even digits
import java.io.*;
import java.util.*;
import java.lang.*;
class GFG
{
// function to return
// the answer when the
// first odd digit is 9
static int trickyCase(String s,
int index)
{
int index1 = -1;
// traverse towards the left
// to find the non-8 digit
for (int i = index - 1; i >= 0; i--)
{
// index digit
int digit = s.charAt(i) - '0';
// if digit is not 8,
// then break
if (digit != 8)
{
index1 = i;
break;
}
}
// if on the left side of the
// '9', no 8 is found then we
// return by adding a 2 and 0's
if (index1 == -1)
return 2 * (int)Math.pow(10, s.length());
int num = 0;
// till non-8 digit
// add all numbers
for (int i = 0; i < index1; i++)
num = num * 10 + (s.charAt(i) - '0');
// if non-8 is even or odd
// than add the next even.
if (s.charAt(index1) % 2 == 0)
num = num * 10 +
(s.charAt(index1) - '0' + 2);
else
num = num * 10 +
(s.charAt(index1) - '0' + 1);
// add 0 to right of 9
for (int i = index1 + 1;
i < s.length(); i++)
num = num * 10;
return num;
}
// function to return
// the smallest number
// with all digits even
static int smallestNumber(int n)
{
int num = 0;
String s = "";
int duplicate = n;
// convert the number to
// string to perform operations
while (n > 0)
{
s = (char)(n % 10 + 48) + s;
n /= 10;
}
int index = -1;
// find out the
// first odd number
for (int i = 0; i < s.length(); i++)
{
int digit = s.charAt(i) - '0';
int val = digit & 1;
if (val == 1)
{
index = i;
break;
}
}
// if no odd numbers are there,
// than n is the answer
if (index == -1)
return duplicate;
// if the odd number is 9,
// than tricky case handles it
if (s.charAt(index) == '9')
{
num = trickyCase(s, index);
return num;
}
// add all digits till first odd
for (int i = 0; i < index; i++)
num = num * 10 +
(s.charAt(i) - '0');
// increase the
// odd digit by 1
num = num * 10 +
(s.charAt(index) - '0' + 1);
// add 0 to the right
// of the odd number
for (int i = index + 1;
i < s.length(); i++)
num = num * 10;
return num;
}
// Driver Code
public static void main(String args[])
{
int N = 2397;
System.out.print(smallestNumber(N));
}
}
// This code is contributed
// by Akanksha rai(Abby_akku)
Python3
# Python3 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
def trickyCase(s, index):
index1 = -1;
# traverse towards the left to find
# the non-8 digit
for i in range(index - 1, -1, -1):
# index digit
digit = s[i] - '0';
# if digit is not 8, then break
if (digit != 8):
index1 = i;
break;
# if on the left side of the '9',
# no 8 is found then we return by
# adding a 2 and 0's
if (index1 == -1):
return 2 * pow(10, len(s));
num = 0;
# till non-8 digit add all numbers
for i in range(index1):
num = num * 10 + (s[i] - '0');
# if non-8 is even or odd
# than add the next even.
if (s[index1] % 2 == 0):
num = num * 10 + (s[index1] - '0' + 2);
else:
num = num * 10 + (s[index1] - '0' + 1);
# add 0 to right of 9
for i in range(index1 + 1, len(s)):
num = num * 10;
return num;
# function to return the smallest
# number with all digits even
def smallestNumber(n):
num = 0;
s = "";
duplicate = n;
# convert the number to string to
# perform operations
while (n):
s = chr(n % 10 + 48) + s;
n = int(n / 10);
index = -1;
# find out the first odd number
for i in range(len(s)):
digit = ord(s[i]) - ord('0');
if (digit & 1):
index = i;
break;
# if no odd numbers are
# there, than n is the answer
if (index == -1):
return duplicate;
# if the odd number is 9, than
# tricky case handles it
if (s[index] == '9'):
num = trickyCase(s, index);
return num;
# add all digits till first odd
for i in range(index):
num = num * 10 + ord(s[i]) - ord('0');
# increase the odd digit by 1
num = num * 10 + (ord(s[index]) -
ord('0') + 1);
# add 0 to the right of the odd number
for i in range(index + 1, len(s)):
num = num * 10;
return num;
# Driver Code
N = 2397;
print(smallestNumber(N));
# This code is contributed
# by mits
C#
// C# program to print the smallest integer
// not less than N with all even digits
using System;
class GFG
{
// function to return the answer when
// the first odd digit is 9
static int trickyCase(string s,
int index)
{
int index1 = -1;
// traverse towards the left
// to find the non-8 digit
for (int i = index - 1; i >= 0; i--)
{
// index digit
int digit = s[i] - '0';
// if digit is not 8, then break
if (digit != 8)
{
index1 = i;
break;
}
}
// if on the left side of the
// '9', no 8 is found then we
// return by adding a 2 and 0's
if (index1 == -1)
return 2 * (int)Math.Pow(10, s.Length);
int num = 0;
// till non-8 digit add all numbers
for (int i = 0; i < index1; i++)
num = num * 10 + (s[i] - '0');
// if non-8 is even or odd
// than add the next even.
if (s[index1] % 2 == 0)
num = num * 10 +
(s[index1] - '0' + 2);
else
num = num * 10 +
(s[index1] - '0' + 1);
// add 0 to right of 9
for (int i = index1 + 1;
i < s.Length; i++)
num = num * 10;
return num;
}
// function to return the smallest number
// with all digits even
static int smallestNumber(int n)
{
int num = 0;
string s = "";
int duplicate = n;
// convert the number to
// string to perform operations
while (n > 0)
{
s = (char)(n % 10 + 48) + s;
n /= 10;
}
int index = -1;
// find out the first odd number
for (int i = 0; i < s.Length; i++)
{
int digit = s[i] - '0';
int val = digit & 1;
if (val == 1)
{
index = i;
break;
}
}
// if no odd numbers are there,
// than n is the answer
if (index == -1)
return duplicate;
// if the odd number is 9,
// than tricky case handles it
if (s[index] == '9')
{
num = trickyCase(s, index);
return num;
}
// add all digits till first odd
for (int i = 0; i < index; i++)
num = num * 10 +
(s[i] - '0');
// increase the odd digit by 1
num = num * 10 +
(s[index] - '0' + 1);
// add 0 to the right of the odd number
for (int i = index + 1;
i < s.Length; i++)
num = num * 10;
return num;
}
// Driver Code
public static void Main()
{
int N = 2397;
Console.Write(smallestNumber(N));
}
}
// This code is contributed
// by Akanksha Rai
?>
PHP
<?php
// PHP 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
function trickyCase($s, $index)
{
$index1 = -1;
// traverse towards the
// left to find the
// non-8 digit
for ($i = $index - 1;
$i >= 0; $i--)
{
// index digit
$digit = $s[$i] - '0';
// if digit is not
// 8, then break
if ($digit != 8)
{
$index1 = $i;
break;
}
}
// if on the left side
// of the '9', no 8
// is found then we
// return by adding a 2
// and 0's
if ($index1 == -1)
return 2 * pow(10,
strlen($s));
$num = 0;
// till non-8 digit
// add all numbers
for ($i = 0; $i < $index1; $i++)
$num = $num * 10 +
($s[$i] - '0');
// if non-8 is even or
// odd than add the next even.
if ($s[$index1] % 2 == 0)
$num = $num * 10 +
($s[$index1] - '0' + 2);
else
$num = $num * 10 +
($s[$index1] - '0' + 1);
// add 0 to right of 9
for ($i = $index1 + 1;
$i < strlen($s); $i++)
$num = $num * 10;
return $num;
}
// function to return
// the smallest number
// with all digits even
function smallestNumber($n)
{
$num = 0;
$s = "";
$duplicate = $n;
// convert the number
// to string to perform
// operations
while ($n)
{
$s = chr($n % 10 + 48) . $s;
$n = (int)($n / 10);
}
$index = -1;
// find out the
// first odd number
for ($i = 0;
$i < strlen($s); $i++)
{
$digit = $s[$i] - '0';
if ($digit & 1)
{
$index = $i;
break;
}
}
// if no odd numbers are
// there, than n is the answer
if ($index == -1)
return $duplicate;
// if the odd number
// is 9, than tricky
// case handles it
if ($s[$index] == '9')
{
$num = trickyCase($s, $index);
return $num;
}
// add all digits
// till first odd
for ($i = 0; $i < $index; $i++)
$num = $num * 10 +
($s[$i] - '0');
// increase the
// odd digit by 1
$num = $num * 10 +
($s[$index] - '0' + 1);
// add 0 to the right
// of the odd number
for ($i = $index + 1;
$i < strlen($s); $i++)
$num = $num * 10;
return $num;
}
// Driver Code
$N = 2397;
echo smallestNumber($N);
// This code is contributed
// by mits
?>
JavaScript
<script>
// Javascript 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
function trickyCase(s, index)
{
let index1 = -1;
// traverse towards the left
// to find the non-8 digit
for (let i = index - 1; i >= 0; i--)
{
// index digit
let digit = s[i].charCodeAt() - '0'.charCodeAt();
// if digit is not 8, then break
if (digit != 8)
{
index1 = i;
break;
}
}
// if on the left side of the
// '9', no 8 is found then we
// return by adding a 2 and 0's
if (index1 == -1)
return 2 * Math.pow(10, s.length);
let num = 0;
// till non-8 digit add all numbers
for (let i = 0; i < index1; i++)
num = num * 10 + (s[i].charCodeAt() - '0'.charCodeAt());
// if non-8 is even or odd
// than add the next even.
if (s[index1].charCodeAt() % 2 == 0)
num = num * 10 +
(s[index1].charCodeAt() - '0'.charCodeAt() + 2);
else
num = num * 10 +
(s[index1].charCodeAt() - '0'.charCodeAt() + 1);
// add 0 to right of 9
for (let i = index1 + 1;
i < s.length; i++)
num = num * 10;
return num;
}
// function to return the smallest number
// with all digits even
function smallestNumber(n)
{
let num = 0;
let s = "";
let duplicate = n;
// convert the number to
// string to perform operations
while (n > 0)
{
s = String.fromCharCode(n % 10 + 48) + s;
n = parseInt(n / 10, 10);
}
let index = -1;
// find out the first odd number
for (let i = 0; i < s.length; i++)
{
let digit = s[i].charCodeAt() - '0'.charCodeAt();
let val = digit & 1;
if (val == 1)
{
index = i;
break;
}
}
// if no odd numbers are there,
// than n is the answer
if (index == -1)
return duplicate;
// if the odd number is 9,
// than tricky case handles it
if (s[index] == '9')
{
num = trickyCase(s, index);
return num;
}
// add all digits till first odd
for (let i = 0; i < index; i++)
num = num * 10 +
(s[i].charCodeAt() - '0'.charCodeAt());
// increase the odd digit by 1
num = num * 10 +
(s[index].charCodeAt() - '0'.charCodeAt() + 1);
// add 0 to the right of the odd number
for (let i = index + 1;
i < s.length; i++)
num = num * 10;
return num;
}
let N = 2397;
document.write(smallestNumber(N));
// This code is contributed by divyeshrabadiya07.
</script>
Time Complexity: O(log10N)
Auxiliary Space: O(log10N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem