LeetCode 8: String to Integer (atoi)
来源:互联网 发布:sdrsharp软件下载 编辑:程序博客网 时间:2024/06/05 23:08
String to Integer (atoi)
Implement atoi to convert a string to an integer.
解题思路
本题比较简单,但是需要考虑许多实现细节:
- 字符串为空或者全是空格,返回0;
- 字符串的前缀空格需要忽略掉;
- 忽略掉前缀空格后,遇到的第一个字符,如果是‘+’或‘-’号,继续往后读;如果是数字,则开始处理数字;如果不是前面的2种,返回0;
- 处理数字的过程中,如果之后的字符非数字,就停止转换,返回当前值;
- 在上述处理过程中,如果转换出的值超出了int型的范围,就返回int的最大值或最小值。
class Solution {public: int myAtoi(string str) { int index = 0; int len = str.length(); // 忽略前缀空格 while (index < len && str[index] == ' ') index++; // 字符串为空或者全是空格,返回0 if (index == len) return 0; // 处理+、-号 int sign = 1; if (str[index] == '+' || str[index] == '-') { if (str[index++] == '-') { sign = -1; } } // 开始处理数字 long long sum = 0; while (index < len) { if (str[index] >= '0' && str[index] <= '9') { sum = sum * 10 + sign * (str[index] - '0'); } else { // 遇到的字符非数字,停止转换返回当前值 return sum; } if (sum > INT_MAX || sum < INT_MIN) { //溢出处理 return sum > 0 ? INT_MAX : INT_MIN; } ++index; } return sum; }};
0 0
- LeetCode 8 - String to Integer (atoi)
- [LeetCode 8] String to Integer (atoi)
- leetcode 8STRING 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 8:《String to Integer (atoi) 》
- leetcode.8---------------String to Integer (atoi)
- leetCode #8 String to Integer (atoi)
- [LeetCode Java] 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 8 - String to Integer (atoi)
- leetcode #8 String to Integer (atoi)
- String to Integer (atoi) - LeetCode 8
- spring mvc校验部分属性,springmvc校验属性,java.lang.ClassNotFoundException: com.fasterxml.classmate.Filter
- 1.如何提高tableView的效率
- 重写EditText,使其具有下划线
- 动态添加综合布局---动态添加控件及将某XML动态加入到Activity显示(续)
- 黑马程序员——Java基础语法 之运算符
- LeetCode 8: String to Integer (atoi)
- JavaScript中document.write()的用法
- ANDROID开发之SQLite详解
- lintcode-Remove Linked List Elements-452
- Unity3D-移动
- SSH Tunnel 一般场景用法
- 关于微博的正文的整个思维逻辑
- hadoop学习笔记六 --- mapreduce原理笔记
- PullToRefresh使用详解(五)--下拉刷新的ScrollView