leetcode——String to Integer
来源:互联网 发布:淘宝折扣网站 编辑:程序博客网 时间:2024/06/06 08:46
问题
实现自己的 atoi 字符转换函数。
一直以来都有听说过在面试过程中会问到实现 atoi 函数,现在碰到这题,正好拿来练练手。
思路
核心思路就一条语句:(m 为要返回的整数)
m = m * 10 + str[i] - ‘0’;
需要注意比较多的细节
- 删掉起始空格
- 正符号判断
- 删掉有效字符(0-9数字字符)后面的所有无效字符
- 整数是否溢出
围绕着那条核心语句,一点点将上述四点条件考虑进去,可以写出如下的实现代码:
解决
#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
会发生溢出。
0 0
- LeetCode——String to Integer (atoi)
- LeetCode——String to Integer (atoi)
- String to Integer (atoi) —— Leetcode
- leetcode——String to Integer
- leetcode——String to Integer (atoi)
- LeetCode——8. String to Integer
- LeetCode—8. String to Integer (atoi)
- [LeetCode]String to Integer
- 【Leetcode】String to Integer
- [leetcode] string to integer
- leetcode-string to integer
- Leetcode: String to Integer
- [LeetCode]String to Integer
- LeetCode:String to Integer
- LeetCode--String to Integer
- leetcode string to integer
- [leetcode] String to Integer
- LeetCode-String To Integer
- stm32之pwm输出实验
- Java基础理解
- ISay obj=(ISay)Class.forName(args[0]).newInstance(); obj.say();
- HDU 5630 Rikka with Chess
- Android Wear 进阶 - 3.1 Creating Custom UIs for Wear Devices-Defining Layouts 创建自定义的手表设备UIs-定义布局
- leetcode——String to Integer
- ESB企业服务总线
- iOS编程基础之环境篇
- 自定义用户注册键盘(封装)1
- C/C++程序编译步骤 如何生成可执行文件
- c#委托与事件(详解)
- 例题6-16 UVa10129 Play on Words(欧拉回路)
- 自己动手丰衣足食之Swiper插件
- Prim算法求最小生成树 poj 1258