3 回答

TA貢獻2012條經驗 獲得超12個贊
我這樣解決。優先考慮數據類型long在int只要有在左移溢出的機會。從一開始就處理邊緣情況,以避免在過程中修改輸入值。該算法基于我們過去在學校中使用的除法技術。
public int divide(int AA, int BB) {
// Edge case first.
if (BB == -1 && AA == Integer.MIN_VALUE){
return Integer.MAX_VALUE; // Very Special case, since 2^31 is not inside range while -2^31 is within range.
}
long B = BB;
long A = AA;
int sign = -1;
if ((A<0 && B<0) || (A>0 && B>0)){
sign = 1;
}
if (A < 0) A = A * -1;
if (B < 0) B = B * -1;
int ans = 0;
long currPos = 1; // necessary to be long. Long is better for left shifting.
while (A >= B){
B <<= 1; currPos <<= 1;
}
B >>= 1; currPos >>= 1;
while (currPos != 0){
if (A >= B){
A -= B;
ans |= currPos;
}
B >>= 1; currPos >>= 1;
}
return ans*sign;
}

TA貢獻1815條經驗 獲得超10個贊
與調試器一起運行,發現它abs_dividend
為-2147483648。
那么in的比較結果while (abs_dividend >= abs_divisor) {
為假,count
并且永遠不會遞增。
原來的解釋是在Javadoc中Math.abs(int a)
:
請注意,如果參數等于Integer.MIN_VALUE的值(最負的可表示int值),則結果是相同的值,該值為負。
大概是因為Integer.MAX_VALUE
2147483647,所以無法用來表示正2147483648 int
。(注意:2147483648將是Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
)
添加回答
舉報