Please enable Javascript to view the contents

剑指office(十一)二进制中1的个数

 ·  ☕ 1 分钟  ·  🎅 YSL

题目描述

输入一个整数,输出该数32位二进制表示中1的个数。其中负数用补码表示。

示例1

输入

10

返回值

2
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
public:
     int  NumberOf1(int n) {
         int cout = 0;
         int mark = 0x01;
         while(mark)
         {
             if(mark&n)cout++;
             mark<<=1;
         }
         return cout;
     }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
     int  NumberOf1(int n) {
         int count = 0;
          while(n)
          {
              count++;
              n = (n-1)&n;
          }
         return count;
     }
};