問題描述
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.
思路分析
雖然是Easy題,但感覺并沒有很簡單,主要的點在于不能使用循環(huán)。
解法是用log函數(shù),由于log函數(shù)返回的值是近似值(小數(shù)點后11位小數(shù)),因此要將其與取整的值進(jìn)行比較,差值小于10-11即可認(rèn)為log函數(shù)返回的是整數(shù),即n是3的整數(shù)次冪。
想了一下,能否利用差值小于δ來判斷l(xiāng)og函數(shù)得到的值是整數(shù),在于最小的可能差值是多少。
log3(231-1) = 19.5588...
因此最大的3次冪值是319 = 1162261467
而log31162261468 = 19.0000000007831...
該值與19相差超過0.0000000001。
因此在32位整數(shù)范圍內(nèi),如果log函數(shù)返回值與其取整值差別小于0.0000000001,那么它就是一個真實的整數(shù)。
AC代碼
class Solution(object):
def isPowerOfThree(self, n):
if n > 0:
a = math.log(n, 3)
else:
return False
if abs(a - round(a)) < 0.00000000001:
return True
else:
return False
Runtime: 436 ms, which beats 54.03% of Python submissions.