LeetCode 题解工作台
2 的幂
给你一个整数 n ,请你判断该整数是否是 2 的幂次方。如果是,返回 true ;否则,返回 false 。 如果存在一个整数 x 使得 n == 2 x ,则认为 n 是 2 的幂次方。 示例 1: 输入: n = 1 输出: true 解释: 2 0 = 1 示例 2: 输入: n = 16 输…
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数学·位运算
答案摘要
根据位运算的性质,执行 可以消去二进制形式的 的最后一位 。因此,如果 $n \gt 0$,并且满足 结果为 ,则说明 是 的幂。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·位运算 题型思路
题目描述
给你一个整数 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
提示:
-231 <= n <= 231 - 1
进阶:你能够不使用循环/递归解决此问题吗?
解题思路
方法一:位运算
根据位运算的性质,执行 可以消去二进制形式的 的最后一位 。因此,如果 ,并且满足 结果为 ,则说明 是 的幂。
时间复杂度 ,空间复杂度 。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Clarifies whether negative numbers and zero should return false.
- question_mark
Hints at using bit manipulation rather than iterative loops.
- question_mark
Tests understanding of the mathematical pattern behind powers of two.
常见陷阱
外企场景- error
Not handling zero and negative inputs correctly, returning true incorrectly.
- error
Using iterative multiplication or division without stopping conditions, causing infinite loops.
- error
Relying on floating-point logs without tolerance, leading to incorrect results for large n.
进阶变体
外企场景- arrow_right_alt
Check if a number is a power of three or five using a similar recursive or bit-mimicking approach.
- arrow_right_alt
Return the largest power of two less than or equal to n using bit manipulation.
- arrow_right_alt
Count how many numbers in an array are powers of two using the same n & (n - 1) trick.