题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
#include <iostream>
#include <cstdio>
#include <cstring>
#include<vector>
using namespace std;
class Solution {
public:
     int  NumberOf1(int n) {
         int count=0;
         unsigned int mark=1;        
         while(mark){
             if (n & mark){    //以二进制计算与运算, mark为32位的1
                 count++;
             }
          mark=mark<<1;    将1的左移,依次比较n的二进制形式的每一位
         }
         return count;
     }
};

int main()
{
    Solution sol;
    cout<<sol.NumberOf1(-5);
}

 

相关文章:

  • 2022-02-08
  • 2021-08-27
  • 2022-02-21
  • 2022-12-23
  • 2021-06-28
  • 2021-06-22
  • 2021-12-02
猜你喜欢
  • 2022-12-23
  • 2019-06-20
  • 2022-03-06
  • 2022-02-24
  • 2022-01-21
  • 2021-12-19
  • 2022-01-09
相关资源
相似解决方案