zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    win7+Apache 设置域名指向本地文件夹
    JavaScript 函数式编程
    JS防抖动
    13 个最佳 JavaScript 数据网格库
    js笔试-接收get请求参数
    这10道javascript笔试题你都会么
    60行JavaScript代码俄罗斯方块
    先少谈点人工智能好吗?
    gulp+webpack构建配置
    Gulp和webpack的区别,是一种工具吗?
  • 原文地址:https://www.cnblogs.com/soyscut/p/3883824.html
Copyright © 2011-2022 走看看