StrToInt 最小负数和溢出判断的某坑
把字符串转换成整数
http://www.nowcoder.com/questionTerminal/1277c681251b4372bdef344468e4f26e
这个题我是用DFA做的。但这不是重点,处理溢出才是。
这个函数的目的是让合法不溢出的str,可以一一对应到一个int。
一开始,我是先得到结果的符号,然后再把后续部分当正数处理(突然变负就是溢出),最后乘符号位。但发现用例过不了,这是因为正数和负数不是对称分布的,最后处理符号位会使得最负的数,本来可以表示,却因为其绝对值不能表示而被判非法。
后来改成在刚处理数字位的时候(进入num状态之前),就全程带着符号处理(符号突变就是溢出),解决了判断溢出的问题。
class Solution {
public:
enum stat { begin, posi, nega, zero, num };
int StrToInt(string str) {
int ans = 0;
int final_sign = 1;
stat current = begin;
if (str.size()==0) return 0;
for (auto it = str.begin(); it < str.end(); it++) {
switch (current) {
case begin:
if (*it == '-') { final_sign *= -1; current=nega; continue; }
if (*it == '+') { current = posi; continue; }
if (*it == '0') { current = zero; continue; }
if (*it > '0' && *it < '9') {
current = num;
ans = *it - '0';
ans *= final_sign;
continue;
}
return 0; // invalid
case posi:
if (*it == '-') { final_sign *= -1; current=nega; continue; }
if (*it == '0') { current = zero; continue; }
if (*it > '0' && *it < '9') {
current = num;
ans = *it - '0';
ans *= final_sign;
continue;
}
return 0; // invalid
case nega:
if (*it == '+') { current = posi; continue; }
if (*it == '0') { current = zero; continue; }
if (*it > '0' && *it < '9') {
current = num;
ans = *it - '0';
ans *= final_sign;
continue;
}
return 0; // invalid
case zero:
if (*it == '0') { continue; }
if (*it > '0' && *it < '9') {
current = num;
ans = *it - '0';
ans *= final_sign;
continue;
}return 0; // invalid
case num:
if (*it > '0' && *it < '9') {
ans *= 10;
if(ans >= 0){
ans += *it - '0';
if (ans < 0) return 0;
}
else{
ans -= *it - '0';
if (ans > 0) return 0;
}
continue;
}return 0; // invalid
}
}
return ans;
}
};
查看2道真题和解析