leetcode——String to Integer
2016-02-20 22:02
405 查看
问题
实现自己的 atoi 字符转换函数。一直以来都有听说过在面试过程中会问到实现 atoi 函数,现在碰到这题,正好拿来练练手。
思路
核心思路就一条语句:(m 为要返回的整数)[code]m = m * 10 + str[i] - ‘0’;
需要注意比较多的细节
删掉起始空格
正符号判断
删掉有效字符(0-9数字字符)后面的所有无效字符
整数是否溢出
围绕着那条核心语句,一点点将上述四点条件考虑进去,可以写出如下的实现代码:
解决
[code]#include<iostream> #include<string> using namespace std; int myAtoi(string str) { int m = 0; int flag = 1; std::size_t found = str.find_first_not_of(' '); //cout << "found is: " << found << endl; if(str[found] == '-' || str[found] == '+') { if (str[found] == '-') flag = -1; found++; } for(size_t i = found; i < str.size(); i++) { if(str[i] >='0' && str[i] <= '9') { if (m > 214748364) { if(flag == 1) return 2147483647; else return -2147483648; } if (m == 214748364) { if (flag == 1 && str[i] - '0' > 7) return 2147483647; if (flag == -1 && str[i] - '0' > 8) return -2147483648; } m = m * 10 + str[i] - 48; } else { if (m == 0) return 0; else if(m != 0) { if (flag == -1) return -m; return m; } } } if (flag == -1) return -m; return m; } int main() { cout << "result : " << myAtoi(" -114321") << endl; cout << "result : " << myAtoi(" -114321aaaa") << endl; cout << "result : " << myAtoi(" - 114321aaaa") << endl; cout << "result : " << myAtoi(" asf 123341asdf") << endl; cout << "result : " << myAtoi("+1") << endl; cout << "result : " << myAtoi("-004152aaaa111") << endl; cout << "-2147483648 : " << myAtoi("-2147483648") << endl; cout << "-2147483649 : " << myAtoi("-2147483649") << endl; cout << "2147483647 : " << myAtoi("2147483647") << endl; cout << "2147483648 : " << myAtoi("2147483648") << endl; cout << " -11919730356x : " << myAtoi(" -11919730356x") << endl; return 0; }
另外值得注意的是代码中的数字
2147483647可由
-((1<<31) + 1))得到,并将其设定为一个变量 MAX。而
214748364则可由
MAX%10得到,这样能够增加程序的可读性与自动性。
因为
1<<31的值为
-2147483648,
(1<<31) * 2会发生溢出。
相关文章推荐
- HDU_1874_畅通工程续
- ESB企业服务总线
- HDU 5630 Rikka with Chess
- 一个C#语法高亮插件
- 关于本人:-D(必读)
- 【慕课笔记】第二章 认识JAVA中的字符串 第2节 JAVA中字符串的不变性
- Linux下搭建maven 私服
- Linux Shell+Curl网站健康状态检查脚本,抓出中国博客联盟失联站点
- 单例
- 博客处女篇:stm32之pwm输出实验
- Maven的生命周期
- BZOJ_P1001 [BeiJing2006]狼抓兔子(网络流转换+Dijkstra)
- 线段树(hdu1166)
- Firefox火狐
- 终极基类Object
- Struts2之国际化
- 《Android Studio实用指南》7.1 AndroidStudio代码检查工具概述
- 【狼性文化】
- 1036. 跟奥巴马一起编程
- 遇见 App.Config 、SAE 、 WEB