二进制中1的个数

原文地址:https://www.jianshu.com/p/5c35a9898625

时间限制:1秒 空间限制:32768K

题目描述

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

我的代码

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

运行时间:4ms
占用内存:480k

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

运行时间:3ms
占用内存:376k

原文地址:https://www.cnblogs.com/cherrychenlee/p/10780938.html