LeetCode 题解工作台

4的幂

给定一个整数,写一个函数来判断它是否是 4 的幂次方。如果是,返回 true ;否则,返回 false 。 整数 n 是 4 的幂次方需满足:存在整数 x 使得 n == 4 x 示例 1: 输入: n = 16 输出: true 示例 2: 输入: n = 5 输出: false 示例 3: 输入…

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·位运算

bolt

答案摘要

如果一个数是 的幂次方,那么这个数必须是大于 的。不妨假设这个数是 ,即 ,那么这个数的二进制表示中有且仅有一个 ,且这个 出现在偶数位上。 因此,我们首先判断这个数是否大于 ,然后判断这个数是否是 ,即 与 的按位与结果是否为 ,最后判断这个数的 是否出现在偶数位上,即 与 的按位与结果是否为 。如果这三个条件都满足,那么这个数就是 的幂次方。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个整数,写一个函数来判断它是否是 4 的幂次方。如果是,返回 true ;否则,返回 false

整数 n 是 4 的幂次方需满足:存在整数 x 使得 n == 4x

 

示例 1:

输入:n = 16
输出:true

示例 2:

输入:n = 5
输出:false

示例 3:

输入:n = 1
输出:true

 

提示:

  • -231 <= n <= 231 - 1

 

进阶:你能不使用循环或者递归来完成本题吗?

lightbulb

解题思路

方法一:位运算

如果一个数是 44 的幂次方,那么这个数必须是大于 00 的。不妨假设这个数是 4x4^x,即 22x2^{2x},那么这个数的二进制表示中有且仅有一个 11,且这个 11 出现在偶数位上。

因此,我们首先判断这个数是否大于 00,然后判断这个数是否是 22x2^{2x},即 nnn1n-1 的按位与结果是否为 00,最后判断这个数的 11 是否出现在偶数位上,即 nn0xAAAAAAAA\textit{0xAAAAAAAA} 的按位与结果是否为 00。如果这三个条件都满足,那么这个数就是 44 的幂次方。

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

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

复杂度分析

指标
时间complexity ranges from O(1) for bit manipulation to O(log n) for division or recursion. Space complexity is O(1) for iterative solutions and O(log n) for recursion due to call stack usage.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Ask about distinguishing power of two versus power of four with bit operations.

  • question_mark

    Probe candidate understanding of position of the set bit in powers of four.

  • question_mark

    Expect efficient solutions rather than brute force iterations or floating-point checks.

warning

常见陷阱

外企场景
  • error

    Checking only n > 0 or n & (n - 1) without verifying bit position can misidentify powers of two as powers of four.

  • error

    Using floating-point logarithms may introduce precision errors in edge cases.

  • error

    Failing to handle n = 1 correctly, which is a valid power of four (4^0).

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Power of Two check without enforcing power of four constraints.

  • arrow_right_alt

    Power of Eight verification requiring similar bit and math insights.

  • arrow_right_alt

    Recursive-only solution without bit manipulation optimizations.

help

常见问题

外企场景

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