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

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

檢查 int 變量是否在 Java 中溢出或下溢

檢查 int 變量是否在 Java 中溢出或下溢

紅顏莎娜 2022-11-30 17:01:50
我需要從頭開始創建一個 parseInt 方法,到目前為止我已經明白了。唯一的部分是我無法弄清楚如何確定一個 int 變量是溢出還是下溢,如果它是然后在 Java 中拋出 IllegalArgumentException。為了更好地理解這是我的任務:創建靜態方法 parseInt(String) 將字符串轉換為 int 值,正值或負值。方法在...時拋出 IllegalArgumentException字符串包含除“-”之外的非數字字符(作為字符串的第一個字符)。字符串只有 '-' 而沒有數字。字符串表示一個太大而無法存儲為整數并產生溢出的數字字符串表示一個數字太小而不能作為整數存儲并產生下溢這是我到目前為止所擁有的 /** * Convert a string into an integer value * @param str The string to be converted * @return answer * @throws IllegalArgumentException if answer is underflowing or overflowing */public static int parseInt(String str) throws IllegalArgumentException {    int answer = 0, factor = 1;    int i = 0;    for (i = str.length()-1; i >= 0; i--) {        answer += (str.charAt(i) - '0') * factor;        factor *= 10;    }    boolean isNegative = false;    if(str.charAt(0) == '-') {        isNegative = true;    }    if (answer > Integer.MAX_VALUE) throw new IllegalArgumentException();    if (answer < Integer.MIN_VALUE) throw new IllegalArgumentException();    if (isNegative) {        answer = -answer;    }    return answer;}
查看完整描述

1 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

這不需要使用long


public static int parseInt(String str) throws IllegalArgumentException {

    int answer = 0, factor = 1;


    boolean isNegative = false;

    if(str.charAt(0) == '-') {

        isNegative = true;

    }


    for (int i = str.length()-1; i >= (isNegative ? 1 : 0); i--) {

        int nextInt = (str.charAt(i) - '0') * factor;


        if(isNegative && answer > Math.abs(Integer.MIN_VALUE + nextInt))

            throw new IllegalArgumentException();

        else if(!isNegative && answer > Integer.MAX_VALUE - nextInt)

            throw new IllegalArgumentException();


        answer += nextInt;

        factor *= 10;

    }


    if (isNegative) {

        answer = -answer;

    }


    return answer;

}


查看完整回答
反對 回復 2022-11-30
  • 1 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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