扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
8. String to Integer (atoi)
创新互联建站主营吴兴网站建设的网络公司,主营网站建设方案,成都app开发,吴兴h5重庆小程序开发搭建,吴兴网站营销推广欢迎吴兴等地区企业咨询
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
题目大意:该题目是说将string类型的字符串转换成整型数据,类似于C++库里的atoi函数,解决该题目的关键在于两个方面:
(1)字符串格式的合法判断
(2)转换结果的溢出判断
首先,对于字符串格式,空格不计入计算,应从第一个非空字符开始判断,首字母只能是符号(+、-)与数字的一种;从计算开始遍历字符串,到最后一位数字为止;
其次,对于转换结果,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范围则返回最大与最小值。所以我们可以开始用long long类型的变量存储结果;
代码如下:
class Solution { public: int myAtoi(string str) { if (str.empty()) return 0; int flag = 1;//flag 1正 -1负 long long result = 0; int i = 0; while (str[i] == ' ') { i++; } if (str[i] == '-') { i++; flag = -1; } else if (str[i] == '+') { i++; } for (int j = i; j < str.length(); j++) { if (str[j] >= '0' && str[j] <= '9') { result = result * 10 + (str.at(j) - '0'); if (result > 2147483647) { if (flag == 1) result = INT_MAX; else { result = INT_MIN; flag = 1; } break; } } else break; } return flag * result; } };
2016-08-09 00:18:49
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流