zoukankan      html  css  js  c++  java
  • 编程之美 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

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

  • 相关阅读:
    fastdfs部署及官网
    fasrdfs在spring cloud中的使用
    面包屑的查询
    SpringCloud中使用ES使用课程上下线
    Redis中在项目中的使用
    树结构Tree查询
    平凡的世界 田晓霞的日记 摘抄

    英语积累
    英语学习第四天
  • 原文地址:https://www.cnblogs.com/FriskyPuppy/p/7891518.html
Copyright © 2011-2022 走看看