String to Integer (atoi)
来源:互联网 发布:网络婚恋诈骗 编辑:程序博客网 时间:2024/04/20 03:39
1、做字符串的题要注意字符串前面是否有空格等其他字符;
2、一个字符串循环结束的标志是遇到’\0’;
3、注意正负的判断;
4、注意正无穷大和负无穷大的判断;
题目:
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这个函数,将字符串转化成一个整数。
注意正负,字符的空格和无穷大的判断,注意细节部分。
代码:
class Solution {
public:
int atoi(string str) {
int flag1=0,flag2=0;
int i=0;
int num=0;
long long cur=0;
while(str[i]!=’\0’ && str[i]==’ ‘) i++;
for(;str[i]!='\0';i++) { if(str[i]=='-') flag1++, i++; else if(str[i]=='+') flag2++, i++; if(str[i]>='0' && str[i]<='9') { if(flag1==2) { cur=cur*10-(str[i]-'0'); if(cur<-2147483648) return -2147483648; } else if(flag1==1) cur=-str[i]+'0', flag1++; else { cur=cur*10+(str[i]-'0'); if(cur>2147483647) return 2147483647; } } else break; } num=(int)cur; return num;}
};
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- string to integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer(atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- JPA入门例子(采用JPA的hibernate实现版本)
- 学习之旅
- java网络编程中的read阻塞问题
- C语言 关于strcpy和strncpy
- 高速缓存与主存的三种映射方式
- String to Integer (atoi)
- Scala极速入门
- Bridge模式
- apache2多端口设置
- php中通过curl smtp发送邮件
- Java学习笔记(3)——Java的目录结构
- LTE-自适应调制和编码(AMC)
- android ExpandableListView 默认展开
- 完全用Linux工作