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.
    
    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;
        }
    };
  • 相关阅读:
    文件载入功能
    代码调试功能
    实用项
    连贯操作
    AR模式
    表名操作
    字段映射
    ThinkPHP中的模型二
    创建数据对象
    HDU 4888 Redraw Beautiful Drawings(最大流+判最大流网络是否唯一)
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3826992.html
Copyright © 2011-2022 走看看