Leetcode 2413. Smallest Even Multiple
Given a positive integer n
, return the smallest positive integer that is a multiple of both 2
and n
.
Example:
Input: n = 5
Output: 10
Explanation: The smallest multiple of both 2 and 5 is 10.
Input: n = 6
Output: 6
Explanation: The smallest multiple of both 2 and 6 is 6 since 6 is already even.
n
?
n
is a positive integer. To ensure thoroughness, checking the constraints in the problem description would be ideal.To find the smallest positive integer that is a multiple of both 2
and n
, we can use the following observations:
2
and any integer n
is simply 2 * n
if n
is odd.n
is even, n
itself is already a multiple of 2
.Thus, the smallest positive integer that is a multiple of both 2
and n
can be found using:
(2 * n) if (n % 2 != 0)
(n) otherwise
This leads to a simple conditional check in our implementation.
public class SmallestEvenMultiple {
public int smallestEvenMultiple(int n) {
if (n % 2 == 0) {
return n;
} else {
return 2 * n;
}
}
public static void main(String[] args) {
SmallestEvenMultiple sem = new SmallestEvenMultiple();
System.out.println(sem.smallestEvenMultiple(5)); // Output: 10
System.out.println(sem.smallestEvenMultiple(6)); // Output: 6
}
}
The time complexity of this solution is O(1) because:
n % 2
, 2 * n
) are constant time operations.This solution leverages the properties of even and odd numbers to quickly determine the smallest even multiple of any given integer n
. It runs in constant time and meets the problem’s requirements with minimal computational overhead.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?