basic implementation


  • 0
    N

    Time complexity : O(N)

    class Solution {
    public:
        int myAtoi(string str) {
            int res = 0, sign = 0;
            int i = 0;
            while (i < str.length() && str[i] == ' ') {
                i++;
            }
            
            sign = str[i] == '-' ? -1 : 1;
            if (str[i] == '+' || str[i] == '-') {
                i++;
            }
            
            while ( i < str.length() && '0' <= str[i] && str[i] <= '9') {
                if (res > INT_MAX / 10 || (res == INT_MAX / 10 && (str[i] > '7'))) {
                    return sign > 0 ? INT_MAX : INT_MIN;
                }
                
                res = res * 10 + (str[i] - '0');
                i++;
            }
            
            return sign * res;
        }
    };
    

Log in to reply
 

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