给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。
整数 n 是 3 的幂次方需满足:存在整数 x 使得 n == 3x
示例 1:
输入:n = 27
输出:true
示例 2:
输入:n = 0
输出:false
进阶:
你能不使用循环或者递归来完成本题吗?
官方解法:https://leetcode-cn.com/problems/power-of-three/solution/3de-mi-by-leetcode/
解法:
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 0:
return False
while n % 3 == 0:
n = n//3
return n == 1
官网还给出了其他三种解法,太考验数学功底了,很难想出来。。。
力扣 (LeetCode)链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnsdi2/