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;
         }
     };
     
  • 相关阅读:
    PetaPoco 使用总结(一)
    sql查询语句时怎么把几个字段拼接成一个字段
    js传入和传出参数乱码
    js事件
    耳机没有声音
    JQuery $未定义
    SQL Server导入导出不丢主键和视图的方法
    Transact-SQL解析和基本的实用语句
    数据库索引原理
    Web Service基本概念
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3639371.html
Copyright © 2011-2022 走看看