Leetcode:String to Integer (atoi)

戳我去解题

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 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.

 

 

 1 class Solution {

 2 public:

 3     int atoi(const char *str) {

 4         assert(str != NULL);

 5         const char* curr = str;

 6         const int maxRange = 10;

 7         int tmp = 0;

 8         int num = 0;

 9         while(isspace(*curr)) {

10             ++curr;

11         }

12         const char* start = nullptr;

13         char sign;

14         if (*curr == '-' || *curr == '+') {

15             sign = *curr;

16             ++curr;

17             start = curr;

18         }  else {

19             start = curr;

20         }

21         

22         while (isdigit(*curr)) {

23             tmp = num;

24             num = num * 10 + (*curr - '0');

25             ++curr;

26         }

27         int len = 0;

28         if (!isdigit(*curr)) {

29             len = curr - start;

30         }

31         --curr;

32         if (len > maxRange || num < num - *curr) {

33             if (sign == '-') {

34                 return INT_MIN;

35             } else {

36                 return INT_MAX;

37             }

38         }

39         if (sign == '-')  num = -num;

40         return num;

41     }

42 };

这个题目是各种场合都有存在啊,需要考虑的东西非常多:

1. 前导的空格符, 第9行

2. 正负数, 第14行

3. 非数字符,第22行

4. 溢出,第32行

这里对于溢出,我是采用C语言标准库里面非常巧妙的方法。

我们知道对于一个int,它有其对应的表示范围,也就是说它有一个最大的数字位数。

对于int,这个数字是10,即我们计算这个数字字符串的最大位数 :len = curr - start;

如果len > 10, 那么肯定是溢出了。溢出时 如果sign为负,则返回 INT_MIN,如果为正则返回 INT_MAX

如果len < 10, 那么肯定是没有溢出

如果len == 10,我们用一个简单的语句 num < num - *curr 判断一下即可,这里我们先将curr减1 指向最末一个数字符,

如果不溢出,那么肯定是 num <= num + *curr,如果不满足这条件,那么就溢出

你可能感兴趣的:(LeetCode)