LeetCode String to Integer (atoi)

28894 ワード

class Solution {

public:

    int atoi(const char *str) {

        if (str == NULL) return 0;

        long val =0, pos = 0;

        char ch = '\0';

        int stage = 0; // 0-initial, 1-sign-collected, 2-digit-collected, 3-end 

        bool positive = true;

        int pos_threshold = INT_MAX / 10;

        int neg_threshold = INT_MIN / 10;

        while(stage < 3 && (ch = str[pos]) != '\0') {

            switch(stage) {

                case 0: // initial stage

                    if (ch == '-' || ch == '+') {

                        // sign detected

                        positive = ch == '+';

                        stage = 1;

                        pos++;

                    } else if (ch >= '0' && ch <= '9') {

                        // digit detected

                        stage = 2;

                    } else if (ch == ' ' || ch == '\t' || ch == '
') { // leading white space pos++; } else { // other chars, invalid str to convert stage = 3; } ;break; case 1: // sign-collected stage if (ch >= '0' && ch <= '9') { // digit after sign stage = 2; } else { // other chars, invalid str to convert stage = 3; } ;break; case 2: // number detected stage if (ch >= '0' && ch <= '9') { // digits int pre_val = val; if (positive) { val = val * 10 + (ch - '0'); if (pre_val > pos_threshold || val < pre_val) { stage = 3; val = INT_MAX; } } else { val = val * 10 - (ch - '0'); if (pre_val < neg_threshold || val > pre_val) { stage = 3; val = INT_MIN; } } pos++; } else { // other chars, invalid stage = 3; } ;break; } } return val; } };

広い範囲のデータ型を使用していないので、オーバーフローは考慮する必要があります.小さなステータスマシンです.
第2ラウンド:
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.
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(string str) {

 4         int len = str.size();

 5         if (len == 0) {

 6             return 0;

 7         }

 8         int val = 0;

 9         int pre_val = 0;

10         

11         int pos_threshold = INT_MAX/10;

12         int neg_threshold = INT_MIN/10;

13         bool positive = true;

14         

15         int pos = 0;

16         char ch = 0;

17         // 0-inital, 1-sign read, 2-number read, 3-end

18         int stage = 0;

19         while (pos < len && stage < 3) {

20             ch = str[pos];

21             switch(stage) {

22                 case 0: // inital stage

23                     if (ch == '-' || ch == '+') {

24                         // sign read

25                         stage = 1;

26                         positive = ch == '+';

27                         pos++;

28                         continue;

29                     }

30                     if (ch == ' ' || ch == '\t') {

31                         // leading white space

32                         pos++;  //skip them

33                         continue;

34                     }

35                     if (ch >= '0' && ch <= '9') {

36                         // number read

37                         stage = 2;

38                         continue;

39                     }

40                     //other charaters, invalid case

41                     stage = 3;

42                 break;

43                 

44                 case 1: // sign read stage

45                     if (ch >= '0' || ch <= '9') {

46                         // number read

47                         stage = 2;

48                         continue;

49                     }

50                     // other character, invalid case(if space between sign and digit is not permited)

51                     stage = 3;

52                 break;

53                 

54                 case 2: // number read case

55                     if (!(ch >= '0' && ch <= '9')) {

56                         // character is not digit invalid case

57                         stage = 3;

58                         continue;

59                     }

60                     pre_val = val;

61                     val = val * 10 + (ch - '0') * (positive ? 1:-1);

62                     if (positive) {

63                         if (pre_val > pos_threshold || val < pre_val) {

64                             // overflow

65                             val = INT_MAX;

66                             stage = 3;

67                             continue;

68                         }

69                     } else {

70                         if (pre_val < neg_threshold || val > pre_val) {

71                             val = INT_MIN;

72                             stage = 3;

73                             continue;

74                         }

75                     }

76                     pos++; // next character

77                     break;

78             }

79         }

80         return val;

81     }

82 };

私はどんなに退屈でそんなに長く書いているのか、それとも状態を乱用してはいけないのか、簡単に書いてください.
class Solution {

public:

    int myAtoi(string str) {

        int res = 0;

        bool neg = false;

        int len = str.size();

        int stage = 0;

        

        int pos = 0;

        char ch = 0;

        // skip white spaces

        while (pos < len && str[pos] == ' ') {

            pos++;

        }

        // try read sign

        if (pos < len && (str[pos] == '-' || str[pos] == '+')) {

            neg = str[pos++] == '-';

        }

        // read digits

        while (pos < len && str[pos] >= '0' && str[pos] <= '9') {

            int old = res;

            if (neg) {

                res = res * 10 - (str[pos] - '0');

                if (res > old || old < INT_MIN/10) {

                    res = INT_MIN;

                    break;

                }

            } else {

                res = res * 10 + str[pos] - '0';

                if (res < old || old > INT_MAX/10) {

                    res = INT_MAX;

                    break;

                }

            }

            pos++;

        }

        

        return res;

    }

};