题目

class Solution {
public:
    int strToInt(string str) {
        if(str.size()==0)return 0;       //空字符串情况
        int cur=0;                       
        while(str[cur]==' ')cur++;       //直接从非空字符开始处理
        bool overflow=false;
        bool minus=false;
        unsigned int ans=0;
        if(str[cur]=='+'){               //字符串首位的'+' '-'分别处理
            cur++;
        }else if(str[cur]=='-'){
            cur++;
            minus=true;
        }
        while(str[cur]>='0'&&str[cur]<='9'){         //1.不需要str[cur]-'0'>=0&&str[cur]-'0'<=9这么麻烦  2.不要漏了等号=
            int temp=str[cur]-'0';
            if((ans>(INT_MAX-temp)/10&&minus==false)||(ans>((unsigned int)INT_MIN-temp)/10&&minus==true)){      //判断是否溢出,从ans*10+temp>INT_MAX变形而来
               overflow=true;
               break; 
            }
            ans=ans*10+temp;           //将字符串转化为整数的公式
            cur++;
        }
        if(overflow==false&&minus==false) return ans;         //包含了字符串首位不合法的情况(即也是overflow==false&&minus==false)
        if(overflow==false&&minus==true) return -ans;
        if(overflow==true&&minus==false) return INT_MAX;
        else return INT_MIN;
    }
};

以上代码转自力扣评论区

posted on 2023-07-19 22:24  孜孜不倦fly  阅读(11)  评论(0)    收藏  举报