zoukankan      html  css  js  c++  java
  • [leetcode]String to Integer (atoi) @ Python

    原题地址:https://oj.leetcode.com/problems/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.

    解题思路:atoi的实现,有很多细节需要注意。两个判断条件很关键。INT_MAX/10 >= sum和INT_MAX - digit >= sum这两个判断条件确保了不会溢出。

    代码:

    class Solution:
        # @return an integer
        def atoi(self, str):
            INT_MAX = 2147483647; INT_MIN = -2147483648
            sum = 0
            sign = 1
            i = 0
            if str == '':
                return 0
            while i < len(str) and str[i].isspace():
                i += 1
            if i < len(str) and str[i] == '-':
                sign = -1
            if i < len(str) and (str[i] == '-' or str[i] == '+'):
                i += 1
            while i < len(str) and str[i].isdigit():
                digit = int(str[i])
                if INT_MAX/10 >= sum:
                    sum *= 10
                else:
                    if sign == 1:
                        return INT_MAX
                    else:
                        return INT_MIN
                if INT_MAX - digit >= sum:
                    sum += digit
                else:
                    if sign == 1:
                        return INT_MAX
                    else:
                        return INT_MIN
                i += 1
            return sign*sum
  • 相关阅读:
    简单二分求解(木板补漏问题)
    switch语句和for循环
    JAVA运算符和优先级
    JAVA数据类型
    JAVA基础
    JAVA开发环境
    linux配置IP地址
    LVM逻辑分区
    用户和用户组
    第一天
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3777806.html
Copyright © 2011-2022 走看看