C++ solution without using long long


  • 0
    S

    Solving using long integer is easy but you can check overflow without using long integer.

    class Solution {
    public:
        void trim(string &str){
            while(str[0]==' ')str.erase(str.begin());
        }
        int myAtoi(string str) {
            int neg = 0;
            trim(str);
            if(str[0]=='-' || str[0]=='+'){
                if(str[0]=='-') neg=1;
                str.erase(str.begin());
            }
            int ans = 0;
            for(int i=0;i<str.size();i++){
                if(isdigit(str[i])){
                    int x=str[i]-'0';
                    
                    if(neg == 0 and ans > INT_MAX/10)return INT_MAX;
                    if(neg == 1 and -ans < INT_MIN/10)return INT_MIN;
                    
                    ans = ans * 10;
                    
                    if(neg == 0 and ans > INT_MAX - x)return INT_MAX;
                    if(neg == 1 and -ans < INT_MIN + x)return INT_MIN;
                    
                    ans = ans + x;
                }
                else break;
            }
            if(neg){
                ans = ans * -1;
            }
            return ans;
        }
    };
    

Log in to reply
 

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