题目:
Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3^x.
给定一数,判断它是否是3的次方
这题除了底数换成3,跟231.根本一模一样
class Solution: def isPowerOfThree(self, n: int) -> bool: if n<=0: #0和负数不在讨论範围 return False while n%3==0: n=n//3 return n==1
将一数不断除三直到不能整除
看最后结果是不是1,就知道该数是不是3的次方了
最后执行时间77ms(faster than 96.06%)
一样也可以import math用log下去解
import mathclass Solution: def isPowerOfThree(self, n: int) -> bool: if n<=0: #0和负数不在讨论範围 return False return (math.log10(n)/math.log10(3))%1==0
透过log的性质,我们可以知道log3(3的次方数)会是整数
且log10(n)/log10(3)=log3(n)
所以我们只要计算log10(n)/log10(3)再用%1判断是不是整数即可
最后执行时间60ms(faster than 99.86%)
那我们下题见