AcWing 87. 把字符串转换成整数(C++)- 字符串处理、模拟

AcWing 87. 把字符串转换成整数(C++)- 字符串处理、模拟,第1张

题目链接:https://www.acwing.com/problem/content/83/
题目如下:

class Solution {
public:
    int strToInt(string str) {
        str.erase(0,str.find_first_not_of(' '));
        
        int maxval=INT32_MAX;
        int minval=INT32_MIN;
        long res=0;
        int pos=0;
        int flag=1;
        
        if(str[pos]=='+'){flag=1;pos++;}
        else if(str[pos]=='-'){flag=-1;pos++;}
        
        while(pos<str.size()&&isdigit(str[pos])){
            res=res*10+str[pos++]-'0';
            if(flag*res>=maxval) return maxval;
            if(flag*res<=minval) return minval;
        }
        
        return (int)flag*res;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/717576.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存