Leetcode [8. String to Integer (atoi)]
来源:互联网 发布:foreach遍历二维数组 编辑:程序博客网 时间:2024/06/08 18:02
Problem:8. String to Integer (atoi)
Question
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.
思路
考虑以下几种情况
纯数字类型"012213" -> 12213字符串有其他符号情况"222.22" -> 222"abcd222" -> 0"22aba2323"-> 22带有正负号情况"+222.22" -> 222"-22" -> -22空格情况" 1212" -> 1212" +12 123123" -> 12
操作流程
1. 首先除掉字符串前面的空格
2. 如果前面有正负号,优先处理好正负号
3. 截取前面的数字部分做转化(如果字符串最前面的子串是数字,截止到第一个非数字字符)
4. 考虑是否溢出
代码
class Solution {public: int myAtoi(string str) { eraseEmptyCharater(str); int flag = 1; int overflow = false; if (str.size() !=0 && str[0] == '-') flag = -1; preprocess(str); if(str.size() == 0) return 0; int result = 0; int exp = str.size()-1; for(int i = 0; i < str.size(); i++) { if (unsigned(result) + unsigned((int(str[i])-48) * pow(10, exp)) > INT_MAX) overflow = true; result += (int(str[i])-48) * pow(10, exp); exp--; } if(overflow) return flag == 1 ? INT_MAX : INT_MIN; return result*flag; } void eraseEmptyCharater(string &str) { int i = 0; for (; i < str.size(); i++) { if (str[i] != ' ') break; } str = str.substr(i, str.size()-i); } void preprocess(string &str) { if(str[0] == '+' || str[0] == '-') str = str.substr(1, str.size()-1); string vocabulary = "0123456789"; int lastDigPos = -1; for(int i = 0; i < str.size(); i++) { if (vocabulary.find(str[i]) != string::npos) lastDigPos++; else break; } str = str.substr(0, lastDigPos+1); }};
阅读全文
0 0
- [LeetCode]8. String to Integer (atoi)
- LeetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) Leetcode Python
- LeetCode --- 8. String to Integer (atoi)
- LeetCode 8.String to Integer (atoi)
- [Leetcode] 8. String to Integer (atoi)
- [leetcode] 8.String to Integer (atoi)
- [LeetCode] 8.String to Integer (atoi)
- <LeetCode OJ> 8. String to Integer (atoi)
- leetCode 8. String to Integer (atoi)
- 8. String to Integer (atoi) LeetCode
- leetcode 8. String to Integer (atoi)
- leetcode 8. String to Integer (atoi)
- LeetCode OJ 8.String to Integer (atoi)
- Leetcode ☞ 8. String to Integer (atoi)
- 8. String to Integer (atoi) ---Leetcode
- leetcode 8. String to Integer (atoi)
- Leetcode: 8. String to Integer (atoi)(JAVA)
- Linux 文件目录
- 集群计算
- 子div 的margin-top不生效
- 旅游租赁蓝海市场,平衡车租赁前景探讨
- 云主机Linux系统部署Apache Web服务
- Leetcode [8. String to Integer (atoi)]
- codevs3143二叉树的序遍历
- Layout POJ
- 史上最优秀的,最快的编辑器VIM(上古神器)
- 解决shadowsocks2.8.2报错问题
- Eclipse中设置作者日期等信息
- 用c语言实现的猜数字小游戏
- 4888. 【NOIP2016提高A组集训第14场11.12】最近公共祖先 (2017.10B组)
- CNN卷积神经网络中的AlexNet、VGG、GoogLeNet、ResNet对比