码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 191. Number of 1 Bits ☆(位 1 的个数)

时间:2019-04-12 16:24:36      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:style   als   int   count   known   public   tar   etc   turn   

描述

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;
    }
}

 

[LeetCode] 191. Number of 1 Bits ☆(位 1 的个数)

标签:style   als   int   count   known   public   tar   etc   turn   

原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10696657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!