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?
log運算。
//Runtime: 18 ms
public class Solution {
public boolean isPowerOfThree(int n) {
double res = Math.log(n) / Math.log(3);
return Math.abs(res - Math.round(res)) < 1e-10;
}
}
Given an integer, write a function to determine if it is a power of two.
2的n次方,必然大於0;而且二進制位中只有一個1。
public class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & n - 1) == 0;
}
}