字符串转成整型(int)
2015-08-23 12:52
260 查看
1 题目
Implement atoito convert a string to an integer.Hint: Carefullyconsider all possible input cases. If you want a challenge, please do not seebelow and ask yourself what are the possible input cases.
Notes: It isintended for this problem to be specified vaguely (ie, no given input specs).You are responsible to gather all the input requirements up front.
Requirements for atoi:
The functionfirst discards as many whitespace characters as necessary until the firstnon-whitespace character is found. Then, starting from this character, takes anoptional initial plus or minus sign followed by as many numerical digits aspossible, and interprets
them as a numerical value.
The string cancontain additional characters after those that form the integral number, whichare ignored and have no effect on the behavior of this function.
If the firstsequence of non-whitespace characters in str is not a valid integral number, orif no such sequence exists because either str is empty or it contains onlywhitespace characters, no conversion is performed.
If no validconversion could be performed, a zero value is returned. If the correct valueis out of the range of representable values, INT_MAX (2147483647) or INT_MIN(-2147483648) is returned.
2 分析
(1) 空字符串返回0;(2) 去除字符串前边的0;
(3) 若遇到非数字字符则终止计算;
(4) 若求出的数越界则返回最大值或者最小值。
3 实现
int atoi(string str) { int start = str.find_first_not_of(' '); if (start > 0) { str = str.substr(start); } int size = str.size(); if (0 == size) { return 0; } int signal = 1; int i = 0; if (str[i] == '+') { ++i; } else if (str[i] == '-') { signal = -1; ++i; } long long res = 0; while (i < size) { if (str[i] < '0' || str[i] > '9') { break; } res = res * 10 + (str[i] - '0'); if (res > INT_MAX) { return signal == 1 ? INT_MAX : INT_MIN; } ++i; } return res * signal; }
相关文章推荐
- 黑马程序员-------Java笔记--------怎么越过泛型检查
- storm trident merger
- HEX文件格式详解
- 输入三个整数,按从小到大顺序输出,用引用做形参
- Count and Say
- 如何在VC++中使用Windows Forms (VS2012-VS2015)
- 【随便写写】为什么可以O(m)地得到C(n,m)
- 2014 International Conference on Robotics and Computer Vision (ICRVC 2014)
- UIButton2
- [读评]互联网时代方法论:企业独裁与民主的边界
- 编写高质量代码改善C#程序的157个建议——建议123:程序集不必与命名空间同名
- Nginx - Windows下Nginx基本安装和配置
- android sdk中自带的json
- EntityFramework之孩子删除(四)(你以为你真的懂了?)
- 7 天玩转 ASP.NET MVC — 第 6 天
- 百度贴吧看到的,笑话与哲理 《泰罗奥特曼与佛像》
- Nagios
- CSS loading动画插件收集
- 互联网 免费的WebService接口
- java反射学习总结