Given an integer, write a function to determine if it is a power of two.

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n == 0) return false;
        if (n == 1) return true;
        if (n % 2 == 1) return false;
        return isPowerOfTwo(n / 2);
    }
}
// Can also use bit manipulation: n && n - 1;
public class Solution {
public boolean isPowerOfTwo(int n) {
if (n > 0 && (n & (n - 1)) == 0) return true;
return false;
}
}
Advertisements