您的位置:首页 > 其它

leetcode - 字符串转换成数字(String to Integer)atoi

2015-08-17 14:39 411 查看
https://leetcode.com/problems/string-to-integer-atoi/

把字符串转换成数字,即实现atoi函数。坑多慎重。

class Solution {
public:
int myAtoi(string str) {
int len = str.length();
int index = 0;
while (index < len && isspace(str[index])) index++;
bool minus = false;
if (index < len && (str[index] == '-' || str[index] == '+')) {
minus = str[index] == '-';
index++;
}
long long result = 0;
// 注意!如果没有下面的强制转换,那么INT_MAX+1溢出了,变成INT_MIN
while (result <= (long long)INT_MAX + 1 && index < len && isdigit(str[index])) {
result = result * 10 + (str[index] - '0');
index++;
}
if (minus) result = -result;
// 不科学的设定
if (result < INT_MIN) return INT_MIN;
if (result > INT_MAX) return INT_MAX;
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: