C++_Accepted


  • 0
       // this problem is so weird.. the requirements are not so clear.. just be aware of following inputs: 
       //"      +-2" = 0
      //"     21474   83648 - " = 21474
    
    class Solution {
    public:
    int myAtoi(string str) {
        long res = 0;
        int n = str.size();
        int sign = 1;
        
        for(int i = 0; i < n;){
            while(str[i] == ' ') {i++;}
            if(str[i] == '-' || str[i] == '+'){
                sign = str[i] =='-' ? -1 : 1;
                i++;
            }
            while(i < n && isdigit(str[i])){
                res = res * 10 + (str[i++] - '0');
                if(res * sign >= INT_MAX) return INT_MAX;
                if(res * sign <= INT_MIN) return INT_MIN;
            }
            return (int)sign*res;
            //this return controls that when the following is a digit, this char could be considered as a digit for the final result, or we should end the loop and return the result;
        }
        return (int)res*sign;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.