zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    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.

    class Solution {
    public:
        int atoi(const char *str) {
            if(str == NULL || str[0] == '') return 0;
            int cur = 0, sign = 0, loc = 0;
            while(str[loc] == ' ')
                loc++;
    
            if(str[loc] == '-') 
            {
                sign = -1;
                loc++;
            }
            else if(str[loc] == '+')
            {
                sign = 1;
                loc++;
            }
            else
                sign = 1;
    
            while(str[loc] != '' && str[loc] >= '0' && str[loc] <= '9')
            {
                int tmp = cur;
                cur = cur * 10 + str[loc++] - '0';
                bool flag = ((cur - str[loc - 1] + '0') / 10) == tmp && cur >= 0; //这里判断溢出的方法不合理
                if(!flag && sign == 1)
                    return INT_MAX;
                else if(!flag && sign == -1)
                    return INT_MIN;
            }
    
            return cur * sign;
        }
    };

    //此题对于溢出的处理可以有两种思路,一种是用long long来存运算结果,防止溢出
    //另外一种是在溢出可能发生前加以判断,代码如下
    class Solution {
     public:
         int atoi(const char *str) {
             // Start typing your C/C++ solution below
             // DO NOT write int main() function
             assert(str != NULL);
             
             while(isspace(*str)) str++;  // remove ' '
                 
                 
             int sign = (*str == '-') ? -1 : 1;
             
             if (*str == '-' || *str == '+')    // if can check one char
                 str++;
                 
             int ret = 0;
             while(isdigit(*str))   // is digit
             {
                 int digit = *str - '0';
                 
                 if (INT_MAX / 10 >= ret)
                     ret *= 10;
                 else
                     return sign == -1 ? INT_MIN : INT_MAX;
                     
                 if (INT_MAX - digit >= ret)
                     ret += digit;
                 else
                     return sign == -1 ? INT_MIN : INT_MAX;
                     
                 str++;
             }
             
             return ret * sign;
         }
     };
     
  • 相关阅读:
    Centos 安装Apache软件
    简单工厂模式和策略模式的差别
    ASCII对比表
    谋哥:这个时代没有比程序猿更适合创业
    Android 自己主动化測试(3)&lt;monkeyrunner&gt; 依据ID查找对象&amp;touch&amp;type (python)
    Java学习笔记七(目录操作)
    我读经典(7):读《程序猿生存定律》有感
    SELECT语句逻辑运行顺序,你知道吗?
    Qt Creator新安装后运行一个程序后,出现错误:Error while building/deploying project dict-qt (kit: Desktop Qt 5.10.0 MinGW 32bit) When executing step "qmake"
    软件的各版本分类介绍
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3639371.html
Copyright © 2011-2022 走看看