LeetCode8. String to Integer (atoi)

The main idea of ​​the title: Implement atoi function, this function is to realize the function of converting strings into integers

Topic Analysis: The key to this question is the handling of special circumstances.

There are too many special cases, but as long as you submit it again and again, you can know which samples your code fails to pass, and then modify the code to cover this sample.

Special example:

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

Code display:

class Solution {
public:
    int myAtoi(string str) {
        long long result = 0;
        bool flag = true;
        int pos = -1;   
        bool temp = false; //indicates whether the first valid symbol appears
        for(int i=0;i<str.length();i++){
            if((str[i]==' '|| str[i]=='0')&&(pos==-1)){ //Indicates that the preceding character is invalid
                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'){ //If there is a non-integer, jump out of the loop
                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]!='- ') //represents a non-significant number
            result = 0;
        return result;
    }
};


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326038119&siteId=291194637