231. Power of Two
Given an integer, write a function to determine if it is a power of two.
S1: brutal force O(logn)
bool isPowerOfTwo(int n) {
if (n < 1) return false;
long p = 1;
while (p < n) {
p *= 2;
}
return p == n;
}
S2: bit manipulation O(1)
若一个数为2的power,则其二进制表示只有1位为1
bool isPowerOfTwo(int n) {
if (n < 1) return false;
return !(n & (n - 1));
}
326. Power of Three
Given an integer, write a function to determine if it is a power of three.
S1: loop
bool isPowerOfThree(int n) {
if (n < 1) return false;
while(n % 3 == 0) {
n = n / 3;
}
return n == 1;
}
S2: hard code
max power of 3 that fits in int is 3^19 = 1162261467
bool isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}