zoukankan      html  css  js  c++  java
  • leetcode 191 位1的个数

     

    可参考博客:https://www.cnblogs.com/AndyJee/p/4630568.html,这个对本问题讨论比较详细,本文只针对leetcode答案和剑指offer答案;

    对无符号整型的难度实际上不高,只需要不断右移与1取与就可以了,代码如下:

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int cnt=0;
            while(n){
                if(n&1) cnt++;
                n>>=1;
            }
            return cnt;
        }
    };

    但是对于有符号就比较麻烦了,因为负数采用补码,右移会在左边补1所以采用直接右移会死循环,但是有个小技巧,采用x&(x-1)可以清楚最低位的1;

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int cnt=0;
            while(n){
                cnt++;
                n=n&(n-1);
            }
            return cnt;
        }
    };
  • 相关阅读:
    第二天续
    使用git提交本地仓库每次需要输入账号密码的问题解决
    第二天
    开启远程之路
    第一天
    第一步了解并且安装配置
    6
    Algorithms
    Algorithms
    Algorithms
  • 原文地址:https://www.cnblogs.com/joelwang/p/10722639.html
Copyright © 2011-2022 走看看