[leetcoide] 【字符串】8. String to Integer (atoi)
来源:互联网 发布:软件售前工程师待遇 编辑:程序博客网 时间:2024/05/21 10:22
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.
题意
将字符串转变为整型数,实现atoi的功能。注意输入的各种情况。
题解
这题没什么难度,就是需要注意几种情况
1、空格符开头的要过滤
2、+、-号开头
3、中间出现非数字字符要中断
4、注意int数的最大最小区间
class Solution {public: int myAtoi(string str) { if(str.size()==0) return 0; int flag=1; unsigned int res=0; int i=0; while(str[i]==' '&&i<str.size()) i++; if(str[i]=='-') { flag=-1; i++; } else if(str[i]=='+') i++; for(;i<str.size();i++) { if(str[i]>='0'&&str[i]<='9') { int cur=str[i]-'0'; if(res>INT_MAX/10|| (res==INT_MAX/10 && cur>INT_MAX%10) ) return flag==-1 ? INT_MIN : INT_MAX; res=res*10+cur; } else break; } return res*flag; }};
0 0
- [leetcoide] 【字符串】8. String to Integer (atoi)
- LeetCode 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)
- react-native android_home配置问题(android)
- mybatis OR语句的写法
- redis订阅发布模式
- cocos2D-X源码分析之从cocos2D-X学习OpenGL(15)----帧缓冲
- HTTPS的七个误解
- [leetcoide] 【字符串】8. String to Integer (atoi)
- raspberry内核编译和模块开发
- C++ stl队列Queue用法介绍:删除,插入等操作代码举例
- Linux 文件系统的创建与挂载方法
- Bootstrap插件预览
- mongodb安装教程。
- java中hashCode方法与equals方法的用法总结
- 使用UNIVOCITY-PARSERS创建和读取CSV文件
- 第三方APP微信支付Java服务端构建步骤