zoukankan      html  css  js  c++  java
  • [LeetCode] 191. Number of 1 Bits ☆(位 1 的个数)

    描述

    Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).

    输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数。

    解析

    消除最后的1

    观察一下 n 与 n-1 这两个数的二进制表示:对于 n-1 这个数的二进制来说,相对于 n 的二进制,它的最末位的一个 1 会变成 0,最末位一个 1 之后的 0 会全部变成 1,其它位相同不变。

    比如 n = 8888,其二进制为 10001010111000

    则 n - 1 = 8887 ,其二进制为 10001010110111

    通过按位与操作后:n & (n-1) = 10001010110000

    也就是说:通过 n&(n-1)这个操作,可以起到消除最后一个1的作用。

    所以可以通过执行 n&(n-1) 操作来消除 n 末尾的 1 ,消除了多少次,就说明有多少个 1 。

    简单遍历

    每次与&1,如果为1,说明最后一位为1,再右移一位。

    代码

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int cnt = 0;
            while(n != 0){
                cnt++;
                n = n & (n - 1);
            }
            return cnt;
        }
    }
    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            while (n != 0) {
                count += (n & 1);
                n = n >>> 1;
            }
            return count;
        }
    }
  • 相关阅读:
    2014 12 27 bestcoder 第一题
    大数阶乘问题!
    学校acm比赛题
    hdu1002 大数相加问题
    写于创建之初
    Linux指令 vi编辑,保存及退出
    Java基础-反射
    Java基础-接口与多态
    00023-layui表单有check、radio、switch,未选中时值不提交的解决
    00022-layui 显示表单,iframe父子页面传值
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10696657.html
Copyright © 2011-2022 走看看