231. 2 的幂
给你一个整数 n
,请你判断该整数是否是 2 的幂次方。如果是,返回 true
;否则,返回 false
。
如果存在一个整数 x
使得 n == 2x
,则认为 n
是 2 的幂次方。
示例 1:
输入:n = 1 输出:true 解释:20 = 1
示例 2:
输入:n = 16 输出:true 解释:24 = 16
示例 3:
输入:n = 3 输出:false
示例 4:
输入:n = 4 输出:true
示例 5:
输入:n = 5 输出:false
提示:
-231 <= n <= 231 - 1
进阶:你能够不使用循环/递归解决此问题吗?
原站题解
golang 解法, 执行用时: 0 ms, 内存消耗: 1.9 MB, 提交时间: 2023-09-15 14:37:29
func isPowerOfTwo(n int) bool { const big = 1 << 30 return n > 0 && big%n == 0 }
java 解法, 执行用时: 0 ms, 内存消耗: 38.5 MB, 提交时间: 2023-09-15 14:37:12
class Solution { static final int BIG = 1 << 30; public boolean isPowerOfTwo(int n) { return n > 0 && BIG % n == 0; } }
python3 解法, 执行用时: 44 ms, 内存消耗: 15.9 MB, 提交时间: 2023-09-15 14:36:55
class Solution: BIG = 2**30 def isPowerOfTwo(self, n: int) -> bool: return n > 0 and Solution.BIG % n == 0
python3 解法, 执行用时: 32 ms, 内存消耗: 16 MB, 提交时间: 2023-09-15 14:36:31
class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and (n & -n) == n
golang 解法, 执行用时: 0 ms, 内存消耗: 1.9 MB, 提交时间: 2023-09-15 14:36:12
func isPowerOfTwo(n int) bool { return n > 0 && n&-n == n }
rust 解法, 执行用时: 0 ms, 内存消耗: 2.2 MB, 提交时间: 2023-09-15 14:34:58
impl Solution { pub fn is_power_of_two(n: i32) -> bool { n > 0 && (n & (n - 1)) == 0 } }
cpp 解法, 执行用时: 0 ms, 内存消耗: 6.4 MB, 提交时间: 2023-09-15 14:34:47
class Solution { public: bool isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } };
java 解法, 执行用时: 0 ms, 内存消耗: 38.8 MB, 提交时间: 2023-09-15 14:33:58
class Solution { public boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } }
golang 解法, 执行用时: 0 ms, 内存消耗: 1.9 MB, 提交时间: 2023-09-15 14:33:41
func isPowerOfTwo(n int) bool { return n > 0 && (n & (n - 1)) == 0 }
python3 解法, 执行用时: 40 ms, 内存消耗: 15.8 MB, 提交时间: 2023-09-15 14:33:01
class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and (n & (n - 1)) == 0
php 解法, 执行用时: 4 ms, 内存消耗: 15.1 MB, 提交时间: 2021-05-14 17:09:28
class Solution { /** * @param Integer $n * @return Boolean */ function isPowerOfTwo($n) { return $n > 0 && ($n&($n-1)) == 0; } }