编程之美 2.1 求二进制中1的个数

  题目链接: 编程之美

  题目描述: 求二进制中1的个数

  解题思路: 如果我们要统计1的个数, 最容易想的方法就是所有位都遍历一遍, 这里要说的是最优的方法是遍历一遍所有的1, 之前做过的lowbit函数的作用就是只保留最后一位1, 这样我们每次lowbit一下, 再将这个数字从原来的数字当中减去, 就是遍历了一遍所有的1, 维护一下次数就可以了。 我代码实现的是方法二, a & (a-1)与上面的想法正好是消除了最后一位1, 一步就达到了目的。 

  代码: 

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;

int solve(int num) {
    int cnt = 0;
    while(num) {
        if(num & 1) {
            cnt++;
        }
        num >>= 1;
    }
    return cnt;
}

int solve2(int num) {
    int cnt = 0;
    while(num) {
        num &= (num-1);
        cnt++;        
    }
    return cnt;
}
int main() {
    int n;
    cin >> n;
    int res = solve2(n);
    cout << res << endl;
    return 0;
}
View Code

  思考: 快两个月没有更新博客了, 一是最近在赛季想多看看书, 二是自己写博客觉得好麻烦........算了, 还是坚持写下去吧

原文地址:https://www.cnblogs.com/FriskyPuppy/p/7891518.html