[LeetCode]8. String to Integer(atoi)
来源:互联网 发布:淘宝产品打折功能收费 编辑:程序博客网 时间:2024/06/03 19:58
Description
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.
Discussion
常规操作。注意一下特殊符号的处理即可。
算法的时间复杂度为O(n)。
C++ Code
class Solution {public: int myAtoi(string str) { //空串返回0 if(str.length() == 0) { return 0; } //用一个long long类型的防止溢出 long long answer = 0; //符号 int sign = 1; int index = 0; const int maxInt = 0x7fffffff; const int minInt = 0x80000000; //跳过空格 while(str[index] == ' ') { index++; } //记录符号,默认为正 if(str[index] == '+') { index++; } else if(str[index] == '-') { index++; sign = -1; } //每次添加一位,并进行溢出判断。若遇到非数字字符,跳出并输出之前的数字。 for(int i = index; i < str.length(); i++) { if(str[i] >= '0' && str[i] <= '9') { answer = answer * 10 + str[i] - '0'; if(answer * sign > maxInt) { return maxInt; } if(answer * sign < minInt) { return minInt; } } else { break; } } answer = answer * sign; return (int)answer; }};
阅读全文
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)
- 【yoyo】Servlet和Filter
- Unity3d背包系统系统(一)——第一个类(Item物品类)
- Merge k Sorted Lists
- UDP协议
- (1)顺序表的操作 ① 输入一组整型元素序列,建立线性表的顺序存储结构。 ② 实现该线性表的遍历。 ③ 在该顺序表中查找某一元素,查找成功显示查找元素,否则显示查找失败。 ④ 在该顺序表中删除或插入指
- [LeetCode]8. String to Integer(atoi)
- 面向对象
- [bzoj 3240--Noi2013]矩阵游戏
- Swift
- Java后台框架篇--Springsecurity(二)
- 2017-09-29校训练题题解
- Java学习之基础训练一
- BZOJ2301 Problemb
- 浅谈数字逻辑代数的基本定理和规矩(一)