【原創】8. String to Integer (atoi) leetcode算法筆記

Implement atoi to convert a string to an integer.


 

step1.去掉空格;

step2.判斷±號;

step3.依次遍歷,如果爲0~9,則base*10加上該數字,將得到的值賦給base。若base大於214746364,或等於214746364並且該數字大於7,說明int溢出,返回2147463647或2147463648;

step4.返回base*sign。

 

具體代碼:

 

public int myAtoi(String str) {
        if (str.isEmpty()) return 0;
        int sign = 1, base = 0, i = 0;
        while (str.charAt(i) == ' ') i++;
        if (str.charAt(i) == '-' || str.charAt(i) == '+') sign = str.charAt(i++) == '-' ? -1 : 1;
        while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
                return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            base = 10 * base + (str.charAt(i++) - '0');
        }
        return base * sign;
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章