問(wèn)題描述
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
補(bǔ)充說(shuō)明:
這個(gè)題目的要求通過(guò)實(shí)現(xiàn)一個(gè)函數(shù),當(dāng)輸入一個(gè)數(shù)字的時(shí)候,如果這個(gè)數(shù)字是3的冪(次方),則返回True。
另外這里有個(gè)小小的要求,就是在實(shí)現(xiàn)功能的前提下,要求盡量不要用循環(huán)或者遞歸實(shí)現(xiàn)。
方案分析
- 首先說(shuō)使用循環(huán)的方式,因?yàn)槭?的冪,肯定滿足的一個(gè)條件就是循環(huán)除以3,肯定有一次能被整除。so easy。上代碼。
python實(shí)現(xiàn)
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n<=0:
return False
while(n%3==0):
n = n / 3
return True if n==1 else False
方案分析2
- 既然會(huì)求冪,反過(guò)來(lái)就是求log了,那么使用log函數(shù)去解決這個(gè)問(wèn)題,但是這里有個(gè)問(wèn)題,看注釋部分。
python實(shí)現(xiàn)2
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
import math
epsilon = 0.000000000000001
if n <= 0:
return False
# return ((math.log(n, 3) + epsilon) % 1 ) <= 2 * epsilon
# 這塊無(wú)效,java可以用,但是python無(wú)效,應(yīng)該是各自的機(jī)制不同,取決于對(duì)浮點(diǎn)數(shù)除法的精度是多少,可以自行試試?;蛘哂泻玫南敕梢粤粞浴? return 3 ** round((math.log(n, 3))) == n