1. 程式人生 > >LeetCode8. 字串轉整數(atoi)

LeetCode8. 字串轉整數(atoi)

題目大意:實現atoi函式,這個函式是實現字串轉成整數的功能

題目分析:本題的關鍵在於特殊情況的處理。

特殊情況實在太多,但只要通過一次次提交,知道自己的程式碼在哪些樣例上通不過,然後修改程式碼使其覆蓋這個樣例即可。

特殊樣例:

""  、"     +004500"  、"+-2"  、"     003"   、"1a"等等

程式碼展示:

class Solution {
public:
    int myAtoi(string str) {
        long long result = 0;
        bool flag = true;
        int pos = -1;   
        bool temp = false;  //表示是否出現了第一個有效的符號
        for(int i=0;i<str.length();i++){
            if((str[i]==' '|| str[i]=='0')&&(pos==-1)){   //表示前面的字元無效
                continue;
            }
            else{
                pos = i;
            }
            if(str[i]=='+' && !temp){
                temp = true;
                continue;
            }
            if(str[i]=='-' && !temp){
                flag = false;
                temp =true;
                continue;
            }
            if(str[i]<'0'||str[i]>'9'){ //出現有 非整數的情況,則跳出迴圈
                break;
            } 
            result = result*10 + (str[i]-'0');
            if(result >= 2147483648){
                result = 2147483648;
                break;
            }
        }
        if(!flag){
            result = 0 - result;
        }
        if(result >= INT_MAX){
            result = INT_MAX; 
        }
        if(str[0]!=' ' && (str[0]<'0' || str[0]>'9') && str[0]!='+' && str[0]!='-')  //表示非有效數字
            result = 0;
        return result;
    }
};