Given an integer, write a function to determine if it is a power of two.
public class Solution {
public boolean isPowerOfTwo(int n) {
return (n > 0) && ((n & (n - 1)) == 0);
}
}
Analysis. This is quite simlple, just to record the number of position which is 1 is 1, then that means this is power of 2.
Also you can use the code to turn the last bit of n which is 1 to 0, and judge if it has been 0
((n & (n - 1))