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

     

    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.

    分析: 非常重要且出名的题目. 有非常多的边界情况要考虑。根据上面的spoiler,已经基本可以将整个流程写出来,但是注意INT_MAX 和 INT_MIN不同,这就造成了当符号不同时,边界不同需要注意

    给出代码:

     1 class Solution {
     2 public:
     3 int atoi(const char *str) {
     4     int num = 0;
     5     bool sign = false;
     6     const int n = strlen(str);
     7     int i = 0;
     8     while (str[i] == ' ' && i < n) i++;
     9     if (str[i] == '+') i++;
    10     else if (str[i] == '-') {
    11         sign = true;
    12         i++;
    13     }
    14     for (; i < n; i++) {
    15         int rec = str[i]-'0';
    16         if (str[i] < '0' || str[i] > '9')
    17             break;
    18         if (num > INT_MAX / 10)
    19         {
    20             return sign?INT_MIN:INT_MAX;
    21         }
    22         
    23         if(num == INT_MAX / 10)
    24         {
    25             if(sign && rec>(INT_MAX%10+1)) return INT_MIN;
    26             else if(!sign && rec>INT_MAX%10) return INT_MAX;
    27         }
    28         num = num * 10 + str[i] - '0';
    29     }
    30     if(sign) num = - num;
    31     return num;
    32 }
    33 };
  • 相关阅读:
    mysql性能分析工具
    vim使用大全
    Vue computed属性
    模板题 + KMP + 求最小循环节 --- HDU 3746 Cyclic Nacklace
    Greedy --- HNU 13320 Please, go first
    DFS --- HNU 13307 Galaxy collision
    HNU 13308 Help cupid
    Linux
    dp
    2015 Multi-University Training Contest 2 1006 Friends
  • 原文地址:https://www.cnblogs.com/soyscut/p/3883824.html
Copyright © 2020-2023  润新知