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
1100&1011 = 1000 用n&(n-1)的方法可以去掉二进制中最右边的1
C++(3ms):
1 class Solution { 2 public: 3 bool isPowerOfTwo(int n) { 4 if(n <= 0) 5 return false ; 6 else 7 return !(n&(n-1)) ; 8 } 9 };
java(2ms):
1 class Solution { 2 public boolean isPowerOfTwo(int n) { 3 return n<=0 ? false : (n&(n-1)) == 0 ; 4 } 5 }