Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
思路:位操作。
public class Solution {
public boolean isPowerOfTwo(int n) {
boolean isPower = false;
int i = 0;
int t;
while (n > 0) {
t = n & 0x1;
if (t == 1) {
i++;
if (i > 1) {
isPower = false;
break;
}
}
n = n >> 1;
isPower = true;
}
return isPower;
}
}