題目
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.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
分析
將一個(gè)字符串轉(zhuǎn)化為一個(gè)整數(shù)坯屿。題意是字符串可能出現(xiàn)各種情況憔古。于是挨個(gè)字符解析性含。
先將前面的空格字符略去鳄虱。然后分析正負(fù)號绎晃,之后判斷是否為數(shù)字字符赁豆,之后將數(shù)字計(jì)算出結(jié)果,當(dāng)溢出時(shí)艺晴,應(yīng)該返回整數(shù)最大和最小值昼钻。
int myAtoi(char* str) {
long long ans=0;
int positive=1;
int length=0;
while(str[length]!='\0'&&str[length]==' ')
{
length++;
}
if(str[length]=='+')
{
positive=1;length++;
}
else if(str[length]=='-')
{
positive=-1;length++;
}
if(str[length]=='\0'||str[length]<'0'||str[length]>'9')
return 0;
else
{
while(str[length]!='\0'&&str[length]>='0'&&str[length]<='9')
{
ans=ans*10+str[length]-'0';
if(ans>2147483648)break;
length++;
}
}
if(positive==1)
{
if(ans>2147483647) return 2147483647;
else return (int)ans;
}
else
{
if(ans>2147483648) return -2147483648;
else return -1*(int)ans;
}
}