Last Updated: 6 Nov, 2020

Closest greater

Easy
Asked in company
Auzmor

Problem statement

Given a positive integer ‘N’, you have to find the closest number to 'N' which is greater than ‘N’, and has at most one non-zero digit. In other words, you have to find a number ‘K’ such that:

1. 'K' should be strictly greater than 'N'.

2. 'K' should contain at most 1 non-zero digit. 

3. Difference between 'N' and 'K' should be minimum. 
For eg.
Consider the number 546. The closest number greater than 546 that contains at most 1 non-zero digit is 600. 
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

The first and the only line of each test case contains a positive integer ‘N’.
Output Format
For each test case, print a single line containing a single integer denoting the number 'K' as described above in a single line. 

The output for each test case will be printed in a separate line.
Note
You don’t have to print anything, it has already been taken care of. Just implement the given function. 
Constraints:
1 <= T <= 1000
1 <= N <= 10 ^ 18

Time limit: 1 second

Approaches

01 Approach

If we see the pattern, we can see that we just have to increment the first digit by one and replace the rest of the digits by zero. 

For example: 

  1. N = 65, Answer = 70
  2. N = 999, Answer = 1000

 

Algorithm: 

  1. Initialise a variable ‘count’ that will store the number of digits of ‘N’.
  2. Store the first digit of ‘N’ in a variable ‘firstDigit’.
  3. Initialise the output variable ‘result’ as firstDigit + 1;
  4. Run a loop ‘count’ - 1 time and keep adding 0 to the ‘result’, i.e keep multiplying ‘result’ by 10.
  5. Return the ‘result’.