亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Java中不使用乘法,除法和mod運算符將兩個整數相除

在Java中不使用乘法,除法和mod運算符將兩個整數相除

瀟瀟雨雨 2021-04-05 13:10:37
我寫下了一個代碼,該代碼在將兩個數相除后不使用商,除法或mod運算符就能找出商。我的密碼public int divide(int dividend, int divisor) {    int diff=0,count=0;    int fun_dividend=dividend;    int fun_divisor=divisor;    int abs_dividend=abs(dividend);    int abs_divisor=abs(divisor);    while(abs_dividend>=abs_divisor){        diff=abs_dividend-abs_divisor;        abs_dividend=diff;        count++;    }    if(fun_dividend<0 && fun_divisor<0){        return count;    }    else if(fun_divisor<0||fun_dividend<0) {        return (-count);    }    return count;}我的代碼通過了像紅利= -1,除數= 1或紅利= 1和除數= -1這樣的測試用例。但它無法通過測試用例,例如股息= --2147483648和除數= -1。但是,當兩個輸入均為負時,我有一個if語句。  if(fun_dividend<0 && fun_divisor<0){        return count;    }當我的輸入是-2147483648和-1時,它返回零。我調試了代碼,發現它無法到達while循環的內部語句。它只是檢查while循環并終止并執行 if(fun_dividend<0 && fun_divisor<0){        return count;    }很明顯,兩個輸入均為負,因此我使用Math.abs函數將它們設為正。但是,當我嘗試查看變量abs_dividend和abs_divisor的值時,它們顯示的是負值。整數最大值可以為9位數字。那么我怎么能通過這個測試用例呢?根據該測試案例,紅利是10位數字,對于整數范圍無效。根據測試用例,我得到的輸出應該是2147483647。我該如何解決該錯誤?
查看完整描述

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;

}


查看完整回答
反對 回復 2021-04-14
?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

與調試器一起運行,發現它abs_dividend為-2147483648。

那么in的比較結果while (abs_dividend >= abs_divisor) {為假,count并且永遠不會遞增。

原來的解釋是在Javadoc中Math.abs(int a)

請注意,如果參數等于Integer.MIN_VALUE的值(最負的可表示int值),則結果是相同的值,該值為負。

大概是因為Integer.MAX_VALUE2147483647,所以無法用來表示正2147483648 int。(注意:2147483648將是Integer.MAX_VALUE + 1 == Integer.MIN_VALUE


查看完整回答
反對 回復 2021-04-14
  • 3 回答
  • 0 關注
  • 376 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號