8. String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

一刷:
測試:

  1. "+-2"
  2. " 123 456"
  3. " -11919730356x"
  4. "2147483647"
  5. "-2147483648"
  6. "2147483648"
  7. "-2147483649"
  8. "+2"

這題的難點在于所有的corner case, 面試時碰到要仔細和面試官多交流

  1. 判斷str是否為空或者長度是否為0
  2. 處理前后的space,也可以用str = str.trim();
  3. 嘗試求出符號sign
  4. 處理數(shù)字
    (1) 假如char c = str.charAt(index)是數(shù)字,則定義int num = c - '0', 接下來判斷是否越界
    1). 當(dāng)前 res > Integer.MAX_VALUE / 10,越界,根據(jù)sign 返回 Integer.MAX_VALUE或者 Integer.MIN_VALUE
    2). res == Integer.MAX_VALUE / 10時, 根據(jù)最后sign和最后一位數(shù)字來決定是否越界,返回Integer.MAX_VALUE或者 Integer.MIN_VALUE
    3). 不越界情況下,res = res * 10 + num
  5. 處理非數(shù)字和‘+’, ‘-’,直接跳到6.
  6. 返回結(jié)果 res * sign
public class Solution {
    public int myAtoi(String str) {
        int res = 0;
        if(str == null || str.length() == 0) return res;
        int neg = 1, digit;
        for(int i=0; i<str.length(); i++){
            str = str.trim();
            if(str.charAt(i)=='-' && i == 0)  neg = -1;
            else if(str.charAt(i)=='+' && i == 0) neg = 1;
            else if(str.charAt(i)<'0' || str.charAt(i)>'9') return neg*res;
            else{
                digit = str.charAt(i) - '0';
                int overflow = overflow(res, digit, neg);
                if(overflow>0 ) return Integer.MAX_VALUE;
                else if(overflow<0) return Integer.MIN_VALUE;
                res = res*10 + digit;
            }
        }
        return res*neg;
        
    }
    
    private int overflow(int res, int digit, int sign){
        if(sign > 0){
           if(res>Integer.MAX_VALUE/10) return 1;
           else if(res == Integer.MAX_VALUE/10 && digit > 7) return 1;
        }
        else{
            if(res>Integer.MAX_VALUE/10) return -1;
            else if(res == Integer.MAX_VALUE/10 && digit > 8) return -1;
        }
        return 0;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容