8. String to Integer (atoi)

ascii to integer的實(shí)現(xiàn)。判斷的方法是進(jìn)位累加。要格外注意'1'和1這樣的char和int的區(qū)別。

  • 有效字符后面的省略。 The string can contain additional characters [after those] that form the integral number, which are ignored and have no effect on the behavior of this function.
  • 首次出現(xiàn)的sequence不是有效數(shù)字,返回0。
  • str為空或者全是空格,返回0。
  • outOfRange的時(shí)候返回INT_MIN/INT_MAX
    public int myAtoi(String str) {
        int total = 0, sign = 1, index = 0;

        if (str == null || str.length() == 0) return 0;

        //jump through spaces
        while (index < str.length() && str.charAt(index) == ' ') index++;

             //或者這么寫:if(total > (Integer.MAX_VALUE - add) / 10) 
        if (str.charAt(index) == '+' || str.charAt(index) == '-') {
            sign = str.charAt(index) == '+' ? 1 : -1;
            index++;
        }

        //計(jì)算方法是進(jìn)位累加
        while (index < str.length()) {
            //易錯(cuò)
            int digit = str.charAt(index) - '0';
            if (digit < 0 || digit > 9) break;
            if (total > Integer.MAX_VALUE / 10 || total == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10) {
                total = sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                break;
            }
            total = total * 10 + digit;
            index++;
        }
        return total * sign;
    }

注意INTMAX和INTMIN分別是2147483647和-2147483648,并不需要分開判斷。很巧妙。

ref:
https://discuss.leetcode.com/topic/12473/java-solution-with-4-steps-explanations

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容