【LeetCode】String-to-int
来源:互联网 发布:选购笔记本 知乎 编辑:程序博客网 时间:2024/06/05 20:05
题目:
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.
翻译:
实现一个atoi函数来把字符串转换为整型变量。
分析:
这道题的AC率只有13.4%,主要是因为对特殊情况的处理上。具体有这么几种情况需要考虑:
1. 多余的空格
2. 判断以“+、-”开头需要做对应的处理
3. 其他非数字字符一旦出现,则忽略该字符以及其后的字符
4. 考虑边界,即是否超出Integer.MAX_VALUE,Integer.MIN_VALUE。
下面的方案采用long作为临时存储,方便做边界的判断。但是还要考虑是否会超出long的最大值,所以采用length长度做初步判断。
int atoi(const char *str) { long long res=0; if(str==NULL) return res; int len=strlen(str); int sign=1; int index=0; while(str[index]==' '||str[index]=='0') { index++; } if(str[index]=='+') index++; else if(str[index]=='-') { sign=-1; index++; } for(;index<len;index++) { char ch=str[index]; if(ch>='0'&&ch<='9') { res=res*10+ch-'0'; if(res>INT_MAX) { if(sign==1) return INT_MAX; else return INT_MIN; } } else { return sign*res; } } return sign*res; }
阅读全文
0 0
- LeetCode: String to Int
- 【LeetCode】String-to-int
- LeetCode 08:string to int(atoi)(C++实现)
- c++ int to string
- String To Int
- string to int
- int to string
- C++: int to string
- int to string
- string to int
- vc int to string
- string to int
- Transform String to Int
- int to string
- java String to int
- C++ int to string
- string to int
- String to int
- 小白开始
- 利用重写url机制简单实现验证码换一张的功能
- Java日期时间
- JVM垃圾回收
- 启动保护模式的程序
- 【LeetCode】String-to-int
- MaterialDesign-Toolbar(五)
- [职业生涯之关于创业与打工]由小摊生意联想到的
- CSU 1563 Lexicography (搜索+组合数)
- 数据结构导论
- hdu 1873 (优先队列)
- Birthday Paradox
- 模板——快速幂
- rapidjson中string使用的一点小坑