二进制中1的个数

题目描述

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

思路

巧用 n&(n-1)

class Solution {
public:
     int  NumberOf1(int n) {
         int count=0;
         while(n){
             count++;
             n=n&(n-1);
         }
         return count;
     }
};
原文地址:https://www.cnblogs.com/zhousong918/p/10276738.html