题目:326. 3 的幂
思路:在n的范围内找到最大的 3的幂,假设为t,那么其他3的幂一定可以整除t。可以预处理出来找出t,这样后面0(1)就能判断了。
C++版本:
class Solution {
public:
int solve(){
long s=1;
long mx=pow(2,31)-1;
while(s*3<mx){
s*=3;
}
return (int)s;
}
bool isPowerOfThree(int n) {
int t=1162261467;
//int t=solve();
return n>0 && t%n==0;
}
};
JAVA版本:
class Solution {
int solve(){
long s=1;
long mx=(long)Math.pow(2,31)-1;
while(s*3<mx){
s*=3;
}
return (int)s;
}
public boolean isPowerOfThree(int n) {
int t=1162261467;
//int t=solve();
return n>0 && t%n==0;
}
}
GO版本:
func isPowerOfThree(n int) bool {
// t:=solve()
t:=1162261467
return n>0 && t%n==0
}
func solve() int {
var s int64 =1
mx:=int64(math.Pow(2,31))-1
for s*3<mx {
s=s*3
}
return int(s)
}