LeetCode 8 - String to Integer (atoi)
2015-07-22 16:08
281 查看
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.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and
interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
My Code
class Solution { public: int myAtoi(string str) { const int length = str.length(); int i = 0; // Escape whitespace character while (str[i] == ' ' || str[i] == '\t') i++; // Check first non-whitespace character int flag = 1; if (str[i] == '+') { flag = 1; i++; } else if (str[i] == '-') { flag = -1; i++; } else if (str[i] < '0' || str[i] > '9') return 0; int result = 0, lastResult; for (; i < length; i++) { if (str[i] >= '0' && str[i] <= '9') { lastResult = result; result *= 10; result += flag * (str[i] - '0'); // Overflow: check if the operation if reversible if (((result - flag * (str[i] - '0')) / 10) != lastResult) if (flag == 1) return INT_MAX; else return INT_MIN; // Overflow: + -> - if (result < 0 && flag == 1) return INT_MAX; // Overflow: - -> + if (result > 0 && flag == -1) return INT_MIN; } else break; } return result; } };
Runtime: 8 ms
相关文章推荐
- PHP技术开发微信公众平台
- 作为计算机行业新人的思考
- coc游戏服务器架构分析
- 实现简单的MVC模式,通过一个小例子,不是很完美,但是可以说明一部分的问题
- .Net学习笔记----2015-07-22(C#基础复习10,面向对象2个小练习)
- C语言,题目:函数调用,内存,malloc找错
- LeetCode
- oracle语句块
- GRE写作必备句型
- 2012年5月SAT香港真题解析
- 常用css缩写
- Maven-dependency
- jeecms日志说明
- Android ActionBar完全解析,使用官方推荐的最佳导航栏(上)
- (修改)中文分词
- nmon监控Linux服务器性能
- TCP、UDP、HTTP、SOCKET之间的区别
- 解决"应用程序无法启动,因为应用程序的并行配置不正确"问题
- poj 1847 Tram
- php -- 对象遍历