8. String to Integer (atoi) (重要)
2016-07-11 19:40
295 查看
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
signature accepts a
reset your code definition.
注意5点。
1.空字符串
2.字符串前的空格
3.+-号
4.非法字符(这里返回非法字符前的有效位)
5.溢出(这里如果大于最大,返回最大;小于最小返回最小)
class Solution {
public:
int myAtoi(string str) {
int len = str.size();
if (len == 0) return 0;
long long sum = 0;
int i = 0;
while (str[i] == ' ') i++;
int minus = 1;
if (str[i] == '-'){
minus = -1;
i++;
}
else if (str[i] == '+'){
i++;
}
for (; i < len; i++){
if (str[i]<'0' || str[i]>'9'){
break;
}
sum = sum*10 + (str[i] - '0')*minus;
if (sum>INT_MAX){
return INT_MAX;
}
else if (sum < INT_MIN){
return INT_MIN;
}
}
return sum;
}
};
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.
注意5点。
1.空字符串
2.字符串前的空格
3.+-号
4.非法字符(这里返回非法字符前的有效位)
5.溢出(这里如果大于最大,返回最大;小于最小返回最小)
class Solution {
public:
int myAtoi(string str) {
int len = str.size();
if (len == 0) return 0;
long long sum = 0;
int i = 0;
while (str[i] == ' ') i++;
int minus = 1;
if (str[i] == '-'){
minus = -1;
i++;
}
else if (str[i] == '+'){
i++;
}
for (; i < len; i++){
if (str[i]<'0' || str[i]>'9'){
break;
}
sum = sum*10 + (str[i] - '0')*minus;
if (sum>INT_MAX){
return INT_MAX;
}
else if (sum < INT_MIN){
return INT_MIN;
}
}
return sum;
}
};
相关文章推荐
- 【Redis】配置redis主从复制
- HDU 2136
- java的基本数据类型
- Mac安装homebrew时遇到权限问题
- 绘制圆形头像或图片
- Matlab GUI 鼠标响应(三)
- KeyValue与KeyData与KeyCode区别(转)
- (转)C#特性学习与使用(为枚举定义Description)
- 腾讯云CentOS7.0使用yum安装mysql
- 小sugar呀____DAY4:总结
- 视频添加滤镜的预览和导出
- 在线教育测试的相关
- [小技巧]自定义图片的圆角
- Redis 分区
- 投票的选择
- WPF动态添加按钮并相应事件。
- 文件上传之本地预览
- tushare module 3 -- 股票分类数据
- 初探Vue原理之view-model的数据动态双向绑定
- hdu 5108(数论-整数分解)