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