Skip to content

Latest commit

 

History

History
135 lines (97 loc) · 2.28 KB

File metadata and controls

135 lines (97 loc) · 2.28 KB
comments difficulty edit_url rating source tags
true
简单
1144
第 311 场周赛 Q1
数学
数论

English Version

题目描述

给你一个正整数 n ,返回 2 n 的最小公倍数(正整数)。

 

示例 1:

输入:n = 5
输出:10
解释:5 和 2 的最小公倍数是 10 。

示例 2:

输入:n = 6
输出:6
解释:6 和 2 的最小公倍数是 6 。注意数字会是它自身的倍数。

 

提示:

  • 1 <= n <= 150

解法

方法一:数学

如果 $n$ 为偶数,那么 $2$$n$ 的最小公倍数就是 $n$ 本身。否则,$2$ 和 $n$ 的最小公倍数就是 $n \times 2$

时间复杂度 $O(1)$

Python3

class Solution:
    def smallestEvenMultiple(self, n: int) -> int:
        return n if n % 2 == 0 else n * 2

Java

class Solution {
    public int smallestEvenMultiple(int n) {
        return n % 2 == 0 ? n : n * 2;
    }
}

C++

class Solution {
public:
    int smallestEvenMultiple(int n) {
        return n % 2 == 0 ? n : n * 2;
    }
};

Go

func smallestEvenMultiple(n int) int {
	if n%2 == 0 {
		return n
	}
	return n * 2
}

TypeScript

function smallestEvenMultiple(n: number): number {
    return n % 2 === 0 ? n : n * 2;
}

Rust

impl Solution {
    pub fn smallest_even_multiple(n: i32) -> i32 {
        if n % 2 == 0 {
            return n;
        }
        n * 2
    }
}

C

int smallestEvenMultiple(int n) {
    return n % 2 == 0 ? n : n * 2;
}