题目描述
对于本题,我觉得还是需要写一个题解,因为看了yxc大佬的视频,但是个人感觉有不足的地方,因为他是用的long long来做的 ,但是这有一个问题,就是long long也会超过范围,我们不清楚str中的有效的数字有多少位,所以yxc大佬的代码最好能在循环内部加一个判断,更加的稳妥,或者采取我本题的解法,虽然繁琐,但是可以避免数字过大产生的问题。
算法1
(暴力枚举) $O(n)$
C++ 代码
class Solution {
public:
int maxEdge = INT_MAX / 10;
int minEdge = INT_MIN / 10;
int maxSV = INT_MAX % 10;
int minSV = INT_MIN % 10;
int strToInt(string str) {
int n = str.size();
if(n <= 0) return 0;
int left = 0;
bool is_Minus = false;
int res = 0;
while(left < n && str[left] == ' ') left ++ ;
if(str[left] == '+') left ++ ;
else if(str[left] == '-')
{
left ++ ;
is_Minus = true;
}
int k = left;
//cout << k <<endl;
while(k < n && str[k] >= '0' && str[k] <= '9')
{
if(is_Minus){
int t = (- 1) * (str[k] - '0');
if(res < minEdge) return INT_MIN;
if(res == minEdge)
{
if(t < minSV) return INT_MIN;
}
res = res * 10 +t;
}
else
{
int t = str[k] - '0';
//cout << t << endl;
if(res > maxEdge) return INT_MAX;
if(res == maxSV)
{
if(t >= maxSV) return INT_MAX;
}
else res = res * 10 + t;
//cout << res << endl;
}
k++;
}
return res;
}
};