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 };
  • 相关阅读:
    关于setTimeout的妙用
    JavaScript中四种不同的属性检测方式比较
    AngularJS中transclude用法详解
    Token:服务端身份验证的流行方案
    浅析网页meta标签中X-UA-Compatible属性的使用
    谈谈近期学习Nativejs和reactNative的一些感受
    关于EasyUI DataGrid行编辑时嵌入时间控件
    全局程序集缓存工具(Gacutil.exe)用法详解
    JAVA从基础到框架搭建网站
    Swagger UI使用指南
  • 原文地址:https://www.cnblogs.com/soyscut/p/3883824.html
Copyright © 2011-2022 走看看