8. String to Integer(Atoi)
题目:
解答:
关键是注意怎么判定溢出的问题,测试用例一定要保证有INT_MAX, INT_MIN, INT_MAX + 1, INT_MIN - 1;
当然,如果result设置为long long就完全没问题了,但是这样做就太没有难度了
代码:
class Solution {
public:
int myAtoi(string str) {
int result = 0, len = str.size(), sign = 1;
int index = 0;
while(index < len && str[index] == ' ') ++index;
if(index < len && (str[index] == '+' || str[index] == '-'))
{
sign = str[index] == '+' ? 1 : -1;
++index;
}
while(index < len){
if(str[index] > '9' || str[index] < '0')
break;
int remain = str[index] - '0';
if(sign > 0 && (result > INT_MAX / 10 || result == INT_MAX / 10 && remain > 7))
return INT_MAX;
int mintmp = INT_MIN / 10 * -1;
if(sign < 0 && (result > mintmp || result == mintmp && remain > 8))
return INT_MIN;
result = result * 10 + remain;
++index;
}
return sign ? result * sign : result;
}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)