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 };
  • 相关阅读:
    关于read函数的一些分析
    条件变量
    epoll的边缘触发与水平触发
    内核态的接收缓冲区和发送缓冲区
    SourceTreet提交时显示remote: Incorrect username or password ( access token )(4种解决办法)
    前端技术汇总+Vue最新快速上手
    MyBatisPlus性能分析插件,条件构造器,代码自动生成器详解
    博客园怎样在Markdown编辑模式下调整图片大小(已解决)
    MyBatisPlus分页查询,删除操作
    idea括号选中时出现一条下滑线(突出显示)打开或关闭方法
  • 原文地址:https://www.cnblogs.com/soyscut/p/3883824.html
Copyright © 2011-2022 走看看