8.字符串转换整数

class Solution {
    
    
public:
    int myAtoi(string s) {
    
    
        int flag = 1;
        int n = 0;
        s.erase(0, s.find_first_not_of(" "));
        if(s == "" || s == "+" || s == "-") return 0;
        if(s.at(0) == '-'){
    
    
            flag = -1;
            s = s.substr(1);
        }
        else if(s.at(0) == '+'){
    
    
            s = s.substr(1);
        }
        if(s.at(0) >= '0' && s.at(0) <= '9'){
    
    
            for(char c : s){
    
    
                if(c >= '0' && c <='9'){
    
    
                    if((2147483647 - int(c-'0'))/10 < n){
    
    
                        if(flag == 1) return 2147483647;
                        else return -2147483648;
                    }
                    n = n * 10 + int(c-'0');
                }
                else
                    break;
            }
        }
        return n * flag;
    }
};

Accepted
1082/1082 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 87.96 % of cpp submissions (6.8 MB)

猜你喜欢

转载自blog.csdn.net/The_Dan/article/details/121759134
今日推荐