題目:
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 ;
}
};