LeetCode 题解工作台
3 的幂
给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。 整数 n 是 3 的幂次方需满足:存在整数 x 使得 n == 3 x 示例 1: 输入: n = 27 输出: true 示例 2: 输入: n = 0 输出: false 示例 3: 输入…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数学·递归
答案摘要
如果 $n \gt 2$,我们可以不断地将 除以 ,如果不能整除,说明 不是 的幂,否则继续除以 ,直到 小于等于 。如果 等于 ,说明 是 的幂,否则不是 的幂。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·递归 题型思路
题目描述
给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。
整数 n 是 3 的幂次方需满足:存在整数 x 使得 n == 3x
示例 1:
输入:n = 27 输出:true
示例 2:
输入:n = 0 输出:false
示例 3:
输入:n = 9 输出:true
示例 4:
输入:n = 45 输出:false
提示:
-231 <= n <= 231 - 1
进阶:你能不使用循环或者递归来完成本题吗?
解题思路
方法一:试除法
如果 ,我们可以不断地将 除以 ,如果不能整除,说明 不是 的幂,否则继续除以 ,直到 小于等于 。如果 等于 ,说明 是 的幂,否则不是 的幂。
时间复杂度 ,空间复杂度 。
class Solution:
def isPowerOfThree(self, n: int) -> bool:
while n > 2:
if n % 3:
return False
n //= 3
return n == 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Evaluate the candidate's understanding of recursion and iteration.
- question_mark
Check if the candidate can efficiently apply math concepts to solve the problem.
- question_mark
Observe how the candidate handles edge cases like negative numbers and 0.
常见陷阱
外企场景- error
Not handling negative numbers or zero correctly, which can lead to incorrect answers.
- error
Overcomplicating the solution with unnecessary computations when a simpler method exists.
- error
Failing to optimize for large values of n or introducing unnecessary space complexity.
进阶变体
外企场景- arrow_right_alt
Check if n is a power of two instead of three.
- arrow_right_alt
Check if n is a power of an arbitrary integer (other than 3).
- arrow_right_alt
Implement the solution in a language with different recursion limits.