191. Number of 1 Bits

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.

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        
    }
}

Solution:

這題關鍵在于理解注釋里面那句話的意思:雖然傳入的是整型 int n,但你也要當它是 unsigned value。一開始不理解這句話的含義,掛了2^32次方的 case。實際的意思是,傳入了二進制表示為1000 0000 0000 0000 0000 0000 0000 0000的 int,但要當他是 unsigned 的。因為 Java 編譯器會將二進制為1000 0000 0000 0000 0000 0000 0000 0000的 int 解釋為 -(2^31),但題目需要我們當做+2^31處理。

public class Solution
{
    // you need to treat n as an unsigned value
    public int hammingWeight(int n)
    {
        //long num = ((long)n & 0x0ffffffff);
        int num = n;
        int count = 0;
        while(num != 0)  // instead of (num > 0). be careful here.
        {
            if(num % 2 != 0)
            {
                count ++;
            }
            num = num >>> 1;  // instead of >> . be careful here.
        }
        return count;
    }
}

注意1: 不能用 num > 0 做 while 循環(huán)判斷條件,因為最高bit 位為1的 int 被編譯器當做負數(shù),永遠不會進入 while 循環(huán)。
注意2:不能使用 >> 算數(shù)右移,因為最高bit 位為1的 int 用算術右移時,最高位不動,而從最高位右側開始補0,最高位的1永遠不會向左移。要使用 >>> 邏輯you'yi

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容