8. String to Integer (atoi)
来源:互联网 发布:linux个人目录 编辑:程序博客网 时间:2024/06/02 20:46
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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a const char *
argument, please click the reload button to reset your code definition.
唉·,没想到这么简单一个都这么难写。
注意四点情况:
1.输入为空
2.正负号
3.数据溢出
4.空白格
数据溢出不好弄,下面这个方法是利用INT_MAX/10的值和当前result未乘10的值进行比较,判断是否溢出。由于溢出正负极值分别为2147483647 -2147483648,所以为了简练,有两种情况:(1)直接大于INT_MAX/10,说明足够大了,绝对溢出了(2)等于INT_MAX/10,可能会溢出,我们需要再加一个条件判断,是否最后一位大于7。对于正数,2147473648即为最小的溢出值,最后一位大于7。对于负值,如果值为2147483648,虽然没溢出,但是刚好,假设它的值到了这个档次,即时溢出了我们也要返回-2147483648,所以这种情况也应该返回。
class Solution {public: int myAtoi(string str) { if(str.size() == 0) return 0; int result = 0; int sign = 1; int i = 0; while(str[i] == ' ') ++i; if(str[i] == '-' || str[i] == '+') sign = (str[i++] == '-') ? -1 : 1; while(str[i] >= '0' && str[i] <= '9'){ if(result > INT_MAX / 10 || (result == INT_MAX / 10 && str[i]-'0' > 7)){ return sign == 1 ? INT_MAX : INT_MIN; } result = result * 10 + str[i++] - '0'; } return result * sign; } };
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8.String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 8. String to Integer (atoi)
- 九九乘法表
- 区域内点的个数
- 闭锁/栅栏/信号量/FutureTask分析及使用
- 远程链接Ipython Notebook配置
- C/C++经典程序训练5---图形打印问题
- 8. String to Integer (atoi)
- 小鑫の日常系列故事(六)——奇遇记
- 浅析继承
- 6.6 Git 工具 - 子模块
- 客户端主动断开webSocket
- python入门:对象的建立和使用(不涉及继承)
- 自定义View实现联系人快速查找
- 第四章 复合类型(4)
- 基于/proc伪文件系统的读取系统常见内核状态信息