题目:
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函数, 要注意很多要求, 我提交了n遍才被ac。。。。
1.判断空串
2.去除空格
3.第一个非空字符只能是+ , - , 或数字,找到数字后继续遍历直到遇到第一个非数字为止。
4.对于转换结果还要考虑溢出问题
code:
class Solution
{
public:
int myAtoi(string str)
{
if( str.length()==0 ) //判断是否为空串
return 0;
int i=0;
int flag=0; //判断正负
long long res=0;
int max_int = 0x7fffffff;
int min_int = 0x80000000;
while(str[i] == ‘ ‘)
i++;
if(str[i] == ‘+‘)
i++;
else if(str[i] == ‘-‘)
{
flag=1;
i++;
}
while(i!= str.length())
{
if( str[i]-‘0‘>=0 && str[i]-‘0‘ <=9 )
{
res = res*10 + (str[i]-‘0‘);
if( res>max_int )
return (flag==0) ? max_int : min_int;
i++;
}
else
break;
}
return (flag==0) ? res : -res ;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
leetcode String to Integer (atoi)
原文地址:http://blog.csdn.net/nizhannizhan/article/details/46854751