题目:
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.
参考代码:
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX-1)
class Solution
{
public:int atoi(const char *str){if (str == nullptr){return 0;}int position = 0;while (str[position] == ' '){position++;}if (str[position] == '\0'){return 0;}int signal = 1;if (str[position] == '+' || str[position] == '-'){if (str[position] == '-'){signal = -1;}position++;}long long result = 0;// 注意这里是long longwhile (str[position] >= '0' && str[position] <= '9'){result = result * 10 + str[position] - '0';if (result * signal > INT_MAX){return INT_MAX;}if (result * signal < INT_MIN){return INT_MIN;}position++;}return result * signal;}
};