![]() |
VOOZH | about |
Given two integers n and m (m != 0). Find the number closest to n and divisible by m. If there is more than one such number, then output the one having maximum absolute value.
Examples:
Input: n = 13, m = 4
Output: 12
Explanation: 12 is the closest to 13, divisible by 4.Input: n = -15, m = 6
Output: -18
Explanation: Both -12 and -18 are closest to -15, but -18 has the maximum absolute value.
Table of Content
The basic idea is to start checking from n - m to n + m one by one and take the closest number.
12
We first compute the quotient
q = n / m, then calculate two candidates:
n1 = m * q
This is the closest multiple ofmthat is less than or equal ton.n2 = m * (q + 1)orm * (q - 1)
We chooseq + 1orq - 1based on the signs ofnandm:
- If
nandmhave the same sign, usen2 = m * (q + 1)
This moves in the direction towardn, getting the next closest multiple aboven.- If
nandmhave opposite signs, usen2 = m * (q - 1)
This accounts for the fact that increasingqwould move away fromndue to the sign flip, so we instead go backward to get the next closest multiple.Then we return the one (
n1orn2) that has the smaller absolute difference fromn.
- If both have the same distance from
n, return the one with the greater absolute value, as required.
12