LeetCode191 Number of 1 Bits

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 value
public int hammingWeight(int n) {
    long unsignedN = n&0x0FFFFFFFFl;
    short res = 0;
    while (unsignedN>0){
        if((unsignedN&1)==1) res++;
        unsignedN>>=1;
    }
    return res;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章