一、题目
给你一个正整数 n ,返回 2 和 n 的最小公倍数(正整数)。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/smallest-even-multiple/description/
二、C++解法
我的思路及代码
class Solution {
public:
int smallestEvenMultiple(int n) {
if(n%2)
return 2*n;
return n;
}
};
- 时间复杂度:O(1)。仅需要判断一次 n 的奇偶性
- 空间复杂度:O(1)
官方参考代码
class Solution {
public:
int smallestEvenMultiple(int n) {
return n % 2 == 0 ? n : 2 * n;
}
};
- 时间复杂度:O(1)。仅需要判断一次 n 的奇偶性
- 空间复杂度:O(1)