Last Updated: 20 Aug, 2020

Nearest Multiple of 10

Easy
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.
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.

Approaches

01 Approach

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.