LeetCode 题解工作台

2 的幂

给你一个整数 n ,请你判断该整数是否是 2 的幂次方。如果是,返回 true ;否则,返回 false 。 如果存在一个整数 x 使得 n == 2 x ,则认为 n 是 2 的幂次方。 示例 1: 输入: n = 1 输出: true 解释: 2 0 = 1 示例 2: 输入: n = 16 输…

category

3

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·位运算

bolt

答案摘要

根据位运算的性质,执行 可以消去二进制形式的 的最后一位 。因此,如果 $n \gt 0$,并且满足 结果为 ,则说明 是 的幂。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·位运算 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 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

 

进阶:你能够不使用循环/递归解决此问题吗?

lightbulb

解题思路

方法一:位运算

根据位运算的性质,执行 n&(n-1)\texttt{n\&(n-1)} 可以消去二进制形式的 nn 的最后一位 11。因此,如果 n>0n \gt 0,并且满足 n&(n-1)\texttt{n\&(n-1)} 结果为 00,则说明 nn22 的幂。

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and (n & (n - 1)) == 0
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

2 的幂题解:数学·位运算 | LeetCode #231 简单