Skip to main content

Closest Number

Problem​

Given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

Examples:​

Example 1:

Input:
N = 13 , M = 4
Output:
12
Explanation:
12 is the Closest Number to 13 which is divisible by 4.

Example 2:

Input:
N = -15 , M = 6
Output:
-18
Explanation:
-12 and -18 are both similarly close to -15 and divisible by 6. but -18 has the maximum absolute value. So, Output is -18

Your task:​

You don't need to read input or print anything. Your task is to complete the function closestNumber() which takes an Integer n as input and returns the answer.

  • Expected Time Complexity: O(1)O(1)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • βˆ’105<=N<=105-10^5 <= N <= 10^5

Solution​

Python​

def closestNumber(self, N , M):
if M == 0:
return None
quotient = N // M
lower_multiple = M * quotient
upper_multiple = M * (quotient + 1)
if abs(N - lower_multiple) < abs(N - upper_multiple):
return lower_multiple
elif abs(N - upper_multiple) < abs(N - lower_multiple):
return upper_multiple
else:
return max(lower_multiple, upper_multiple, key=abs)

Java​

static int closestNumber(int N , int M) {
int i=0;
while(true){
if((N-i)%M==0)
return N-i;
else if((N+i)%M==0)
return N+i;
else
i++;
}
}

C++​

int closestNumber(int N, int M) {
int r = N % M;
if (r == 0) {
return N;
}
else if (r <= M / 2) {
return N - r;
}
else {
return N + (M - r);
}
}

C​

int closestNumber(int N, int M) {
int r = N % M;
if (r == 0) {
return N;
}
else if (r <= M / 2) {
return N - r;
}
else {
return N + (M - r);
}
}
  • Time Complexity: O(1)O(1)
  • Auxiliary Space: O(1)O(1)