• 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.

    思路:这道题就是把数字字符串转化为数字。首先要跳过前面的空格,然后可能会遇到"+"、"-"记录其标志信息,然后循环遍历数字字符,直到遇到没数字字符或""结束。然后将所得结果与flag标志相乘;左后与INT_MAX和INT_MIN比较。返回结果。

    class Solution {
    public:
        int atoi(const char *str) {
            if(str==NULL)
                return 0;
            int flag=1;
            long long result=0;
            while(*str==' ')
                str++;
            if(*str=='-')
                flag=-1;
            if(*str=='+'||*str=='-')
                str++;
            while(*str>='0'&&*str<='9')
            {
                result=result*10+(*str-'0');
                str++;
            }
            result=flag*result;
            if(result>INT_MAX)
                return INT_MAX;
            else if(result<INT_MIN)
                return INT_MIN;
            return result;
        }
    };
  • 相关阅读:
    看代码写程序
    NP
    一道神题
    找平方数
    凝视
    排队打水
    时间计算
    git客户端下载地址
    iOS GCD
    UIView 和 CALayer的那点事
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3826992.html
Copyright © 2020-2023  润新知