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

阅读 54

2022-04-21

题目链接: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;
    }
};

精彩评论(0)

0 0 举报