Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution(object):
def isPowerOfThree(self, n):
if n == 0:
return False
if n == 1:
return True
if n % 3 != 0:
return False
return self.isPowerOfThree(n/3)
'''这个方法就比较流氓了,找到32位最大的3的幂
if n <= 0:
return False
else:
return 1162261467 % n == 0
'''
#while n > 0:
"""
:type n: int
:rtype: bool
"""

本文提供了一个Python函数,用于确定给定整数是否是3的幂次。该函数采用递归方法实现,并提供了不使用循环或递归的解决方案。通过找到32位最大的3的幂来优化计算过程。
662

被折叠的 条评论
为什么被折叠?



