[LeetCode] 8. String to Integer (atoi)
描述:把字符串转换成整数(实现 atoi)。
思路:逐字符乘 10 累加即可。
提示:
- 应忽略所有前导空白字符;
- 可能有符号标识位;
- 尽可能多地读取数字位;
- 数字位后面可能有无效字符,应全部忽略,不影响此函数的行为;
- 如果字符串无法执行转换,应返回 0;
- 如果转换超出范围,应返回对应的最大值 INT_MAX / 最小值 INT_MIN;
代码:
class Solution {
public:
int myAtoi(string str) {
bool plus = true;
size_t i = 0;
long long tmp = 0;
// skips whitespaces
while(str[i] == ' ' || str[i] == '\t')
i++;
// takes sign character
if(str[i]=='+' || str[i]=='-'){
plus = str[i]=='+';
i++;
}
// reads the integer
while(str[i]>='0' && str[i]<='9'){
tmp *= 10;
tmp += str[i]-'0';
i++;
if(plus){
if(tmp > (long long)INT_MAX){
return INT_MAX;
}
}
else{
if(tmp > (long long)INT_MAX+1){
return INT_MIN;
}
}
}
return plus ? int(tmp) : -int(tmp);
}
};