Nearest Multiple of 10

Easy
0/40
Average time to solve is 15m
profile
Contributed by
10 upvotes
Asked in companies
MicrosoftGreenClouds

Problem statement

You have been given an integer 'N'. Find the nearest multiple of 10 to the given integer 'N'.

Note:
If there are multiple answers, find the smallest one. For example, if N = 35, both 30 and 40 are nearest to N, since 30 is smaller, the expected answer will be 30.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first and only line of each test case or query contains the integer 'N' for which you have to find the nearest multiple of 10.
Output Format:
For each test case, print a single line containing a single integer denoting the nearest multiple of 10.

The output for every test case will be printed in a separate line.

Note:

You are not required to print the expected output, it has already been taken care of. Just implement the given function. 
Constraints:
1 <= T <= 10 ^ 4
0 <= N <= 10 ^ 9

Time Limit: 1 sec.
Sample Input 1:
2
36
13
Sample Output 1:
40
10
Explanation for sample input 1:
For N = 36, from all the multiples of 10 (like 0, 10, 20, ... etc), 40 is nearest to 36. Similarly for N = 13, 10 is the nearest multiple.
Sample Input 2:
1
55
Sample Output 2:
50
Hint

There are only two multiples of 10, nearest to every integer. Try to check them.

Approaches (1)
Nearest two multiples

Every integer has two candidates for the nearest multiple of 10. One is less than or equal to the given number and the other is greater than it.

For example, if the given integer is N = 56, we have 50 and 60 as the candidates for the nearest multiple of 10. So, we will choose the nearest multiple by the following method:

 

  • We will calculate the value of N % 10. Say this value as X (i.e. X = N % 10)
  • Now, if X is less than or equal to 5, then our smaller multiple candidate(i.e. 50 in this case) will be the nearest multiple which can be obtained by N - X
  • If X is greater than 5. Then our larger multiple candidate(i.e. 60 in this case) will be the nearest multiple which can be obtained by N - X + 10

For the above example where N = 56, we have X = 56 % 10 = 6. Now, X is greater than 5, so our nearest multiple of 10 is N - X + 10 = 56 - 6 + 10 = 60.

Time Complexity

O(1).

 

All the operations are done in constant time.

Space Complexity

O(1).

 

No extra space is used.

Code Solution
(100% EXP penalty)
Nearest Multiple of 10
Full screen
Console