【牛客】二进制中1的个数

题目:

二进制中1的个数_牛客题霸_牛客网 (nowcoder.com)

思路:

循环按位与上n-1,循环的次数就是1的个数

代码:

class Solution {
public:
     int  NumberOf1(int n) 
     {
          int temp;
          int count = 0;
          while(n)
          {
               temp = n - 1;
               n &= temp;
               count++;
          }
          return count;
         
     }
};

猜你喜欢

转载自blog.csdn.net/holle_world_ldx/article/details/128323803