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.
Difficulty: Easy
这道题目要考虑多余情况的好多啊,,。。。
int myAtoi(string str) {
int flag=1;
int i = 0;
long long ans = 0;
while(str[i]==' ')
i++;
if(str[i]=='-'||str[i]=='+'){
if(str[i]=='+')
flag = 1;
if(str[i]=='-')
flag = -1;
i++;
}
while(str[i]<='9'&&str[i]>='0'){
ans=ans*10+(str[i]-'0');
i++;
if((ans*flag)>2147483647) return 2147483647;
if((ans*flag)<-2147483648) return -2147483648;
}
ans = ans*flag;
return ans;
}