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;
        }
    };
  • 相关阅读:
    PL/pgSQL的RETURN QUERY例子
    PL/pgSQL的 RETURN NEXT例子
    PL/pgSQL学习笔记之二
    基于React的PC网站前端架构分析
    DialogFragment创建默认dialog
    一个RecycleView的强大adapter
    企业者的福音之8266接入阿里智能,点亮一盏灯。
    基于webmagic的种子网站爬取
    自上而下渐显图片的CSS3实现
    用SwiftGen管理UIImage等的String-based接口
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3826992.html
Copyright © 2011-2022 走看看