leetcode231 Power of Two-zh
# 231. 2 的幂 (opens new window)
English Version (opens new window)
# 题目描述
给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
示例 1:
输入: 1 输出: true 解释: 20 = 1
示例 2:
输入: 16 输出: true 解释: 24 = 16
示例 3:
输入: 218 输出: false
# 解法
# Python3
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
1
2
3
2
3
# Java
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}
1
2
3
4
5
2
3
4
5
# C++
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
};
1
2
3
4
5
6
2
3
4
5
6
# JavaScript
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfTwo = function(n) {
return n > 0 && (n & (n - 1)) == 0;
};
1
2
3
4
5
6
7
2
3
4
5
6
7
# Go
func isPowerOfTwo(n int) bool {
return n > 0 && (n & (n - 1)) == 0
}
1
2
3
2
3
# TypeScript
function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) == 0;
};
1
2
3
2
3
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38