每天一題 leetcode-8 String to Integer (atoi)

每天一道算法題,堅持!

注意點:

1.字符串前面有空格的情況(  '  897')

2.符號位

3.溢出

代碼如下:

class Solution {
public:
    int myAtoi(string str) {
        int minus = 1;
        long long result = 0;
        if(str.length() == 0)
            return 0;
            
        int i=0;
        while(str[i] == ' '){
            if(str[i] == ' ')
                i++;
        }
        
        if(str[i] == '+'){
            i++;
        }else if(str[i] == '-'){
            minus = -1;
            i++;
        }
        
        for(int j = i;j<str.length(); j++){
            if(str[j]>='0' && str[j]<='9'){
                result = result * 10 + str[j] - '0';
                if(result > INT_MAX || result < INT_MIN){
                    return minus<0?INT_MIN:INT_MAX;
                }
            }else{
                break;
            }
        }
        
        return minus * result;
       
    }
};




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