703037. Nearest multiple of 10
Easy
Nearest multiple of 10
Slug: nearest-multiple-of-102437
Difficulty: Easy
Id: 703037
Topic Tags: Arrays, Strings, Mathematical, Data Structures, Algorithms
Company Tags: Microsoft
Summary
Given a number n, find the nearest multiple of 10. The problem requires understanding basic mathematical concepts and algorithmic thinking.
Detailed Explanation
The solution involves calculating the remainder of n when divided by 10 to determine how far it is from the next multiple of 10. If the remainder is less than 5, we need to find the previous multiple of 10; otherwise, we need to find the next multiple of 10.
Here's a step-by-step breakdown:
- Calculate the remainder
rofnwhen divided by 10 using the modulo operator (n % 10). - If
ris less than 5, calculate the previous multiple of 10 as(n - r) / 10 * 10. This will be the nearest multiple of 10. - Otherwise, if
ris greater than or equal to 5, calculate the next multiple of 10 as(n + (10 - r)) / 10 * 10.
Time complexity: O(1) Space complexity: O(1)
Optimized Solutions
Java
public int nearestMultipleOf10(int n) {
int remainder = n % 10;
if (remainder < 5) {
return (n - remainder) / 10 * 10;
} else {
return (n + (10 - remainder)) / 10 * 10;
}
}