leetCode 8. String to Integer (atoi) 字符串
2016-08-09 00:19
405 查看
8. String to Integer (atoi)
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
(1)字符串格式的合法判断
(2)转换结果的溢出判断
首先,对于字符串格式,空格不计入计算,应从第一个非空字符开始判断,首字母只能是符号(+、-)与数字的一种;从计算开始遍历字符串,到最后一位数字为止;
其次,对于转换结果,我们知道整型数据的范围是INT_MIN(-2147482648)到INT_MAX(2147483647),超出范围则返回最大与最小值。所以我们可以开始用long long类型的变量存储结果;
代码如下:
2016-08-09 00:18:49
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
相关文章推荐
- 数据库链接字符串查询网站
- Flex字符串比较 还有Flex字符串操作
- Ruby中创建字符串的一些技巧小结
- ASP下经常用的字符串等函数参考资料
- 将字符串小写转大写并延时输出的批处理代码
- 将字符串转换成System.Drawing.Color类型的方法
- Lua源码中字符串类型的实现
- Lua性能优化技巧(四):关于字符串
- 字符串聚合函数(去除重复值)
- Ruby中的字符串编写示例
- 总结的5个C#字符串操作方法分享
- sqlserver中求字符串中汉字的个数的sql语句
- sql server字符串非空判断实现方法
- C#算法函数:获取一个字符串中的最大长度的数字
- VBS的字符串及日期操作相关函数
- C#实现将千分位字符串转换成数字的方法
- jquery 删除字符串最后一个字符的方法解析
- PowerShell实现在字符串中查找大写字母
- PowerShell中使用Out-String命令把对象转换成字符串输出的例子
- PowerShell中字符串使用单引号和双引号的区别