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;
            }
        }
    };
  • 相关阅读:
    ioncube 加密软件 linux 使用方法
    PHP使用FPDF pdf添加水印中文乱码问题 pdf合并版本问题
    redis windows dll 下载
    浅析PHP7新功能及语法变化总结
    PHP二维数组去重
    extract 用法说明
    python基础之循环
    linux防火墙(五)—— 防火墙的规则备份与还原
    Haproxy搭建Web群集
    网站五层架构
  • 原文地址:https://www.cnblogs.com/jdneo/p/4754214.html
Copyright © 2011-2022 走看看