Skip to content

Latest commit

 

History

History
44 lines (28 loc) · 952 Bytes

simple-fun-181-rounding.md

File metadata and controls

44 lines (28 loc) · 952 Bytes

Simple Fun #181: Rounding 7 Kyu

LINK TO THE KATA - FUNDAMENTALS

Description

Round the given number n to the nearest multiple of m.

If n is exactly in the middle of 2 multiples of m, return n instead.

Example

For n = 20, m = 3, the output should be 21.

For n = 19, m = 3, the output should be 18.

For n = 50, m = 100, the output should be 50.

Input/Output

  • [input] integer n
    1 ≤ n < 10^9.

  • [input] integer m
    3 ≤ m < 109.

  • [output] an integer

Solution

const rounding = (n, m) => {
  const lowerMultiple = n - (n % m)
  const upperMultiple = lowerMultiple + m

  if (n - lowerMultiple === upperMultiple - n) return n

  return n - lowerMultiple < upperMultiple - n ? lowerMultiple : upperMultiple
}