LeetCode191 Number of 1 Bits

来源:互联网 发布:剑雨江湖进阶数据仙羽 编辑:程序博客网 时间:2024/06/02 05:04

LeetCode191 Number of 1 Bits

问题来源LeetCode191

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

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

这道题是计算32bit的int数二进制格式中的1的个数。这个个数又被称为Hamming Weight

Wiki
The Hamming weight of a string is the number of symbols that are different from the zero-symbol of the alphabet used.

Hamming Weight是字符串与所使用的字母的零符号不同的符号的数目。

问题分析

这道题很容易就能想到既然是求32bit中二进制的个数,那么也就是位运算。但是题目中给出 // you need to treat n as an unsigned value 也就是无符号的整型。对于Java程序来说,没有无符号整型的概念,那么应该怎么解决呢。大家可以看另外一篇文章[]

这里就是先将int转化为long,然后通过n&0x0FFFFFFFFl运算,保存无符号的整型。然后通过不断的将数进行右移操作,统计非0的个数。

代码如下

// you need to treat n as an unsigned valuepublic int hammingWeight(int n) {    long unsignedN = n&0x0FFFFFFFFl;    short res = 0;    while (unsignedN>0){        if((unsignedN&1)==1) res++;        unsignedN>>=1;    }    return res;}