C++
去掉二进制最右边的1
1 class Solution { 2 public: 3 /* 4 * @param n: An integer 5 * @return: True or false 6 */ 7 bool checkPowerOf2(int n) { 8 // write your code 9 if ( n <= 0 ){10 return false;11 }12 int m = n&(n-1);13 return m==0?true:false;14 }15 };
C++
统计二进制中的1的个数
1 class Solution { 2 public: 3 /* 4 * @param n: An integer 5 * @return: True or false 6 */ 7 bool checkPowerOf2(int n) { 8 // write your code here 9 int cnt=0;10 if(n <= 0){11 return false;12 }13 while(n!=0){14 cnt += n&1;15 n = n>>1;16 if(cnt == 2){17 return false;18 }19 }20 return true;21 }22 };