LeetCode 8. String to Integer (atoi)(字符串转整数)

原题:

Implement atoi which converts a string to an integer.

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.

  1. 在找到第一个非空字符之前,需要移除掉字符串中的空格字符。如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字符即为整数的值。如果第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。
  2. 字符串可以在形成整数的字符后面包括多余的字符,这些字符可以被忽略,它们对于函数没有影响。
  3. 当字符串中的第一个非空字符序列不是个有效的整数;或字符串为空;或字符串仅包含空白字符时,则不进行转换。
  4. 若函数不能执行有效的转换,返回 0。

Note:

  • Only the space character ’ ’ is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [ 2 31 , 2 31 1 ] . If the numerical value is out of the range of representable values, I N T M A X ( 2 31 1 ) or I N T M I N ( 2 31 ) is returned.

给定一个 32 位有符号整数,将整数中的数字进行反转。

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42

Explanation: The first non-whitespace character is ‘-‘, which is the minus sign.
Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193

Explanation: Conversion stops at digit ‘3’ as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0

Explanation: The first non-whitespace character is ‘w’, which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648

Explanation: The number “-91283472332” is out of the range of a 32-bit signed integer.
Thefore INT_MIN ( 2 31 ) is returned.

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [ 2 31 , 2 31 1 ] . For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

My solution

class Solution:
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """

        real_str = []
        final_str = mark_char = ''
        real_str_list = [x for x in str.split()]

        if not real_str_list:
            return 0
        for x in range(len(real_str_list)):
            found = False
            if found:
                break
            real_str = real_str_list[x]


            if not real_str:
                return 0

            if real_str[0] in ['-', '+']:
                mark_char = real_str[0]
                real_str = real_str[1:]
            if not real_str:
                return 0
            if real_str[0] > '9' or real_str[0] < '0':
                return 0
            else:
                for count in range(len(real_str)):
                    if '0' <= real_str[count] <= '9' or real_str[count] == '.':
                        final_str += real_str[count]
                        found = True
                    elif real_str:
                        break
                    else:
                        pass

            if mark_char:
                final_str = mark_char + final_str

            final_num = round(float(final_str))
            if final_num >= -2 ** 31 and final_num <= 2 ** 31 - 1:
                return final_num
            elif final_num < -2 ** 31:
                return -2 ** 31
            else:
                return 2 ** 31 - 1

Reference solution

题目分析:一脸看去有点懵逼。还好示例给的比较有代表,简单来说就是要在字符串中找到符合要求的数字串!有符号,有范围限制。

越是题目长的题目越不能被吓到!知道了题目的意思,其实这题特别简单,没什么难点,就是列举出各个情况分类即可。注意str.isdigit()方法的应用即可。具体见下注释,小詹给了比较详细的注释,就不过多介绍了。

class Solution:
    def myAtoi(self, string):
        #正负可以用这个+-1处理,最后返回result时乘以sign即可
        sign = 1
        result = 0
        found = False
        n = len(string)
        for char in string:
            # 利用continue跳过开头的空格符
            if not found and char == " ":
                continue
            # 检测到符号-表示负数,sign记为-1
            elif not found and char == "-":
                found = True
                sign = -1
            # 检测到符号+表示正数
            elif not found and char == "+":
                found = True
            # 利用str.isdigit()方法检测字符是否为数字
            elif char.isdigit():
                found = True
                result = result * 10 + int(char)
                # 确定是否超出范围,超出则按照边界输出
                if result > 2147483647 and sign == 1:
                    return 2147483647
                if result > 2147483648 and sign == -1:
                    return -2147483648
            #其他情况,首字符是字母等。跳出,返回result=0
            else:
                break
        return sign * result

Note: 本章节自己需要注意反省的点有:
1. str做判断的时候是与‘0’,‘9’比较大小,而不是直接的数字0或者9,需要单引号,因为str[0]依旧是带单引号的,无法直接与数字0-9做比较;
2. 自己错误地理解了题意,这道题以空格作为切分后,识别出最早出现的一个数字即可,后面的数字就不用管了,如” +0 235”的判定结果应该是0而非是235,自己就是错在先将空格去除化为一连串字符了;
3. 应该学习python如何判定字符是否为数字或字母,以及str与list的互换。

python 判断字符串中字符类型的常用方法

s为字符串
s.isalnum() 所有字符都是数字或者字母
s.isalpha() 所有字符都是字母
s.isdigit() 所有字符都是数字
s.islower() 所有字符都是小写
s.isupper() 所有字符都是大写
s.istitle() 所有单词都是首字母大写,像标题
s.isspace() 所有字符都是空白字符、 、、

判断是整数还是浮点数
a=123
b=123.123

>>>isinstance(a,int) 
True 
>>>isinstance(b,float) 
True 
>>>isinstance(b,int) 
False

python 实现str list array tuple的互换以及join函数的使用

参考 https://blog.csdn.net/Mr_Cat123/article/details/78628175

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/82353383
今日推荐