231.是否为2的平方根 IsPowerOfTwo

Power of Two

 Total Accepted: 3596 Total Submissions: 11779

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.

[思路]

如果是power of two, 则2进制表达中,有且仅有一个1.  可以通过移位来数1的个数, 这里用了一个巧妙的办法, 即判断   N & (N-1) 是否为0. 

[CODE]



  1. public class Solution {
  2. public boolean IsPowerOfTwo(int n) {
  3. return n > 0 && ((n & (n - 1)) == 0 );
  4. }
  5. }





原文地址:https://www.cnblogs.com/xiejunzhao/p/b49c68db2252f3ca7a45fbaabf11aa88.html