231. Power of Two

时间:2015-07-11 07:52:24   收藏:0   阅读:109

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;
  }
}

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!