题目
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
示例 1:
输入: 27输出: true
示例 2:
输入: 0
输出: false
示例 3:
输入: 9
输出: true
示例 4:
输入: 45
输出: false
进阶:
你能不使用循环或者递归来完成本题吗?
答案1
#
# @lc app=leetcode.cn id=326 lang=python3
#
# [326] 3的幂
#
# @lc code=start
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 0:
return False
while n % 3 == 0:
n //= 3
return n == 1
Solution().isPowerOfThree(19684)
# @lc code=end
Note
除法
如果求模不是0则终止判断是否是1
答案2
#
# @lc app=leetcode.cn id=326 lang=python3
#
# [326] 3的幂
#
# @lc code=start
class Solution:
def isPowerOfThree(self, n: int) -> bool:
res = 1
while res < n:
res *= 3
return n == res
Solution().isPowerOfThree(19684)
# @lc code=end
Note
起始是1 每次乘3 如果不比n小了看看是否和n相等,
如果相等说明,是由3乘过来的
答案2
#
# @lc app=leetcode.cn id=326 lang=python3
#
# [326] 3的幂
#
# @lc code=start
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and 1162261467 % n == 0
# @lc code=end
Note
通过查看相关解析,发现了这个解法,用到了数论的知识,3的幂次的质因子只有3,而所给出的n如果也是3的幂次,故而题目中所给整数范围内最大的3的幂次的因子只能是3的幂次,1162261467是3的19次幂,是整数范围内最大的3的幂次
