[英]Does anyone know why my java code doesn't work properly using n=n/2 while n>>1 does?
這是來自leetcode( https://leetcode.com/problems/number-of-1-bits/ )的問題。 此方法用於計算此數字以二進制表示的1。 我嘗試使用n = n / 2,它不會通過每種情況,而n = n >> 1。 有誰知道為什么?
public class Numberof1Bits {
public static void main(String[] args) {
System.out.println(new Numberof1Bits()
.hammingWeight(0b11111111111111111111111111111111));
}
public int hammingWeight(int n) {
int count = 0;
if (n < 0)
count++;
for (int i = 0; i < 31; i++) {
if ((n & 1) == 1)
count++;
n = n >> 1;// while this doesn't work when n=n/2;
}
return count;
}
}
>> 1
將int
除以2,但是使用floor進行舍入,即向負無窮大舍入。 Java語言規范的相關引用:
n >> s的值是帶有符號擴展的右移位s位。 結果值是floor(n / 2 ^ s)。
例如,
20 >> 1 == 10
15 >> 1 == 7 (7.5 is rounded down to 7)
-20 >> 1 == -10
-15 >> 1 == -8 (-7.5 is rounded down to -8)
另一方面,對於/
舍入是朝向零。 這來自Java語言規范:
二元/運算符執行除法,產生其操作數的商。 左手操作數是被除數,右手操作數是除數。
整數除法向0舍入。
例如,
20 / 2 == 10
15 / 2 == 7 (7.5 is rounded down to 7)
-20 / 2 == -10
-15 / 2 == -7 (-7.5 is rounded UP to -7)
對於負奇數整數n
, n /= 2
因此與n >>= 1; n++;
相同n >>= 1; n++;
n >>= 1; n++;
。 n++
將完全改變設置位數的計算。
你使用的是無符號整數。 0xFFFFFFFF = -1。 -1 >> 1 = -1。 -1/2 = 0.對於設置了最高有效位的任何數字,它將失敗。
如果是Java,則>>
運算符執行符號擴展的按位右移。 例如(為清楚起見,我使用8位數字):
0b10111111 >> 1 => 0b11011111
十進制相同:
-65 >> 1 => -33
位向右移動一個位置,最高位保持原樣。 我的示例編號(0b10111111)是十進制的-65。 如果將它除以2,則得到-32。 是的,我們在翻譯中丟失了一點。 /2
執行算術除法,相當於>> 1
僅適用於正數。
在支持無符號整數和無符號右移的語言中,n / 2應該按預期工作。
在java中,因為>>
已經簽名,你可以使用>>>
,它在沒有符號擴展的情況下進行右移,並且可能更快的循環:
public int hammingWeight(int n) {
int count = 0;
while(n != 0) {
if ((n & 1) != 0) {
count++;
}
n = n >>> 1;
}
return count;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.