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

 

相关文章:

  • 2021-05-02
  • 2021-08-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2021-06-12
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-21
  • 2022-01-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案