4ms C++ Machine Independent Solution


  • 1
    R

    This is my C++ code without using long or long to store the result:

    class Solution {
    public:
        int myAtoi(string str) {
            int result = 0, indicator = 1, overflow = INT_MAX / 10;
            string::size_type i = 0;
            while(i < str.size()) {
                i = str.find_first_not_of(' ');
                if(str[i] == '-' || str[i] == '+') {
                    indicator = (str[i++] == '-') ? -1 : 1;
                }
                while(i < str.size() && '0'<= str[i] && str[i] <= '9') {
                    if(result > overflow) {
                        return (indicator == -1) ? INT_MIN : INT_MAX;
                    } else if(result == overflow) {
                        if(indicator == -1 && str[i] - '0' >= INT_MAX % 10 + 1) {
                            return INT_MIN;
                        }
                        if(indicator == 1 && str[i] - '0' >= INT_MAX % 10) {
                            return INT_MAX;
                        }
                    }
                    result = result * 10 + (str[i++] - '0');
                }
                break;
            }
            return result * indicator;
        }
    };
    

    If you have any suggestions, please do let me know.


  • 0
    T

    @rpfly3 Great solution!


Log in to reply
 

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