LeetCode-8: integer string conversion (atoi)

One, Title Description

Here Insert Picture Description
Here Insert Picture Description

Second, the subject of analysis

  • This is a version of the original title of the weakening of the Offer to prove safety
  • First, the cursor is not moved to the first ' 'place, is not the check number or a sign, if not directly returns 0
  • Check whether the digital cursor, not returns 0; otherwise find the string after the cursor in the first digit is not a position or locate the end of the string is terminated
  • Intermediate these two positions into digital characters, setting sumtime variable type is set longto avoid overflow

Third, the subject of discrimination

And then for the original question on why this question had to prove safety weakening Offer

  • Consider the following two cases
    • The string is invalid 0
    • String is correct, the correct result itself is 0

Then how do we distinguish happened in the end what kind of situation? Obviously we can not distinguish
which requires us to set a global flag amount to distinguish when the return value is 0, 0 is returned in the end is right or wrong string returns 0, but did not ask this question

Fourth, problem-solving Code

class Solution {
public:
    int myAtoi(string str) {
        bool IsPos = 1;
        if(!str.size())  return 0;
        int pos = 0;
        while(str[pos] == ' '){
            pos++;
        }
        if((str[pos] == str.size()) || !((str[pos] >= '0' && str[pos] <= '9') || (str[pos] == '+' || str[pos] == '-'))){
            return 0;
        }
        if(str[pos] == '-' || str[pos] == '+'){
            IsPos = (str[pos] == '-' ? 0 : 1);
            pos++;
            if(str[pos] < '0' || str[pos] > '9')
                return 0;
        }
        
        int end = pos;
        while(str[end] >= '0' && str[end] <= '9' && end < str.size()){
            end++;
        }
        long sln = 0;
        for(int i = pos; i < end; i++){
            if(IsPos){
                if(sln * 10 + (str[i] - '0') <= INT_MAX)
                    sln = sln * 10 + (str[i] - '0');
                else
                    return INT_MAX;
            }
            else{
                if(sln * 10 - (str[i] - '0') >= INT_MIN)
                    sln = sln * 10 - (str[i] - '0');
                else   
                    return INT_MIN;
            }
        }
        return sln;
    }

};

6.3.5 Operating results

Here Insert Picture Description

Published 30 original articles · won praise 3 · Views 819

Guess you like

Origin blog.csdn.net/weixin_44587168/article/details/105297253