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;}

};

0 0
原创粉丝点击