231. Power of Two

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

Analysis:
Base 2 representation of 2 is 10, 4 is 100, 8 is 1000. 
  100
&011
--------
  000
If a number is power of 2, it qualifies the property that n & (n - 1) == 0
Solution:  

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

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array