Wednesday, June 7, 2017

231. Power of Two

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



Solution:

The binary representations of the numbers that are power of 2s' are:

2 -> 10
4 -> 100
8 -> 1000
16 -> 10000

And all these numbers are positive numbers.



Code:


public class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
}