題目原文:
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.
spoilers alert...click to show requirements for atoi.
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 opthion 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 avalid 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.
題意:實現atoi
數字開頭可能有空格
有符號
中間有字母處理字母之前的數字
比較大小的話用longlong就沒問題了
解答:
class solution
{
public:
int atoi(const char* str)
{
int num = 0;
int sign = 1;
const int n = strlen(str);
int i = 0;
while (str[i] == ' '&&i < n)
i++;
if (str[i] == '+') //判斷正負號
i++;
if (str[i] == '-')
{
sign = -1;
i++;
}
for (; i < n; i++)
{
if (str[i]<'0' || str[i]>'9')
break;
if (num>INT_MAX / 10 || (num == INT_MAX / 10 && (str[i] - '0') > INT_MAX % 10))
{
return sign == -1 ? INT_MIN : INT_MAX;
}
num = num * 10 + str[i] - '0';
}
return num*sign;
}
};
注意:在寫的時候會出現C4146錯誤,不妨將#define INT_MIN -2147483648寫成#define INT_MIN (-2147483647-1).(具體原因是跟數據存儲有關,這里不再探究)