326. Power of Three

Total Accepted: 18416
Total Submissions: 52117
Difficulty: Easy

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?

Java:

1
2
3
4
5
public class Solution {
    public boolean isPowerOfThree(int n) {            
        return n==Math.pow(3, (int)Math.round(Math.log10(n)/Math.log10(3)));
    }
}

更好的当然是这个了

1
2
3
4
5
public class Solution {
    public boolean isPowerOfThree(int n) {
        return n>0&&1162261467%n==0;
    }
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。