Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
Follow up: Could you do it without using any loop / recursion?
这道题要求判断一个数是不是3的幂。直接用循环,每次除以3判断最后是否为1即可。
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n==0:
return False
while n % 3 == 0:
n = n / 3
if n != 1:
return False
else:
return True
但Follow up要求不使用循环或者递归,想了半天实在想不出来。看了一眼别人的方法,原来使用n = 3logn3 即可做出。注意因为python有精度误差,比如log3(243),结果应该是5,但是最后算出来的结果会是4.999999,因此需要用round函数来进行四舍五入。
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n <= 0:
return False
if n == 1:
return True
if n >= 3:
return 3 ** round(math.log(n,3)) == n
else:
return False