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