zoukankan      html  css  js  c++  java
  • 【LeetCode】8. 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.

    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.

    提示:

    此题的难点在于各种特殊情况的处理:

    • 忽略开头的空白字符;
    • 忽略第一串连续数字后的所有非法字符;
    • 注意正负号的处理;
    • 如果数字的大小超出了int的范围,则根据其正负,返回 INT_MAX (2147483647) 或 INT_MIN (-2147483648)。

    代码:

    class Solution {
    public:
        int myAtoi(string str) {
            long result = 0;
            int indicator = 1;
            for (int i = 0; i<str.size();)
            {
                i = str.find_first_not_of(' ');
                if (str[i] == '-' || str[i] == '+')
                    indicator = (str[i++] == '-') ? -1 : 1;
                while (isdigit(str[i]))
                {
                    result = result * 10 + (str[i++] - '0');
                    if (result*indicator >= INT_MAX) return INT_MAX;
                    if (result*indicator <= INT_MIN) return INT_MIN;
                }
                return result*indicator;
            }
        }
    };
  • 相关阅读:
    js 动态 activex 组件
    nodejs 任务调度使用
    javascript 停止事件冒泡以及阻止默认事件冒泡
    使用SQL字符串反转函数REVERSE巧妙实现lastindexof功能
    morris.js 简单学习
    weblogic启动受管服务器报错Authentication for user weblogic denied (weblogic 11g 域账号密码不生效的解决方法)
    正向代理与反向代理【总结】
    不休息的工作都是浪费时间
    Oracle实例名,服务名等概念区别与联系
    Tomcat启动找不到JRE_HOME的解决方法
  • 原文地址:https://www.cnblogs.com/jdneo/p/4754214.html
Copyright © 2011-2022 走看看