zoukankan      html  css  js  c++  java
  • LeetCode String to Integer (atoi)

    class Solution {
    public:
        int atoi(const char *str) {
            if (str == NULL) return 0;
            long val =0, pos = 0;
            char ch = '';
            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]) != '') {
                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 == '	' || 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;
        }
    };

    没有使用大范围的数据类型,溢出需要考虑好,是个小状态机

    第二轮:

    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 == '	') {
    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;
        }
    };
  • 相关阅读:
    房地产英语 Real estate词汇
    自制Flash FLV视频播放器
    .net反编译工具Reflector下载
    JQUery插件thickbox
    50 Great Photoshop Tutorials for Clever Beginners
    AspNet中你或许不知道的技巧(转)
    常用的设计网站(收藏)
    35 Green and Earthy Photoshop Effects
    使用 ASP.NET 2.0 增强网站的安全性
    asp.net中实现登陆的时候用SSL
  • 原文地址:https://www.cnblogs.com/lailailai/p/3982764.html
Copyright © 2011-2022 走看看