LeetCode 题解工作台

3 的幂

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

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·递归

bolt

答案摘要

如果 $n \gt 2$,我们可以不断地将 除以 ,如果不能整除,说明 不是 的幂,否则继续除以 ,直到 小于等于 。如果 等于 ,说明 是 的幂,否则不是 的幂。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·递归 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个整数,写一个函数来判断它是否是 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

 

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

lightbulb

解题思路

方法一:试除法

如果 n>2n \gt 2,我们可以不断地将 nn 除以 33,如果不能整除,说明 nn 不是 33 的幂,否则继续除以 33,直到 nn 小于等于 22。如果 nn 等于 11,说明 nn33 的幂,否则不是 33 的幂。

时间复杂度 O(log3n)O(\log_3n),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        while n > 2:
            if n % 3:
                return False
            n //= 3
        return n == 1
speed

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

3 的幂题解:数学·递归 | LeetCode #326 简单