String to Integer

LeetCode #8


Description:

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Example:

Note

Idea:

注意

  1. leading space
  2. 正负号
  3. 不是数的别的symbol
  4. overflow

Code:

class Solution {
public:
    int myAtoi(string str) {
        int sign=1;
        int maxDiv10=INT_MAX/10;

        int i=0;
        while(i<str.size()&&str[i]==' ')  // Take care of the leading spaces
            i++;

        if(i==str.size()) return 0;

        if(str[i]=='+'){ // Take care of the sign
            i++;
        }
        else if(str[i]=='-'){
            i++;
            sign=-1;
        }
        int num=0;
        while(i<str.size()&&isdigit(str[i])){
            int digit=str[i]-'0';
            if(num>maxDiv10 || (num==maxDiv10&&digit>=8) ) // Take care of the overflow case
                return sign==1? INT_MAX: INT_MIN;

            num = num*10 + digit;
            i++;
        }
        return sign*num;
    }
};

results matching ""

    No results matching ""