231. Power of Two

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.

2的次方的特点是只有一位是1,因此n&(n-1)==0则证明只有一个1.

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

posted on 2015-07-11 06:35  shini  阅读(205)  评论(0编辑  收藏  举报

导航