• 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;
        }
    };
  • 相关阅读:
    [Jweb] JSP-编程 06, 内置对象
    [Jweb] Tomcat 解决编码, 乱码问题
    [Jweb] JSP-编程 05 JSP 使用 javabean
    [Jweb] JSP-编程 04 转向 jsp:forward 与 sendRedirect
    [Jweb] JSP-编程 03 静态, 动态包含
    [Jweb] JSP-编程 02 (Directive-include)
    [Jweb] JSP-编程 01 (Directive-page)
    [Jweb] JSP 编程 00 -Declaration- Scriptlet-表达式-Directive (推出原因 : Servlet写标签非常麻烦!)
    [Jweb] 数据库处理以及在 Servlet 中使用 Bean
    [Jweb] Application / TestServletContext.java
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3826992.html
Copyright © 2020-2023  润新知