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:

  1. Calculate the remainder r of n when divided by 10 using the modulo operator (n % 10).
  2. If r is less than 5, calculate the previous multiple of 10 as (n - r) / 10 * 10. This will be the nearest multiple of 10.
  3. Otherwise, if r is 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

View on GeeksforGeeks
public int nearestMultipleOf10(int n) {
    int remainder = n % 10;
    if (remainder < 5) {
        return (n - remainder) / 10 * 10;
    } else {
        return (n + (10 - remainder)) / 10 * 10;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.