4.2.3 LeetCode字符串类题目选做(3) —— String to Integer (atoi) & Integer to English Words

这一节是关于字符串和数字的解析的两个题目,往往要求我们不要用内置的类型转换函数。

8. String to Integer (atoi)

Implement atoi which converts a string to an integer.

具体要求简述:字符串开始可以有多个空格,然后是可能有的+/-号以及多个数字,如" -42",解析为对应的数字。

注意的是:数字后,可以有其他字符,可以忽略,如"4193 with words";如果第一个非空字符不符合条件,或者字符串中没有可解析的数字等,返回0,如"words and 987";最后,如果解析的数字超出int值范围,返回对应的上限/下限。

题目解析:

认真分析上述限制条件,将各种情况处理好即可;注意的是数字字符的解析用ord函数。代码如下:

class Solution:
    def myAtoi(self, strs):
        """
        :type str: str
        :rtype: int
        """
        flag = 1
        sign = 0
        num = 0
        for char in strs:
            if flag:
                if char == ' ':
                    continue
                elif char == '-' or char == '+':
                    sign = 1 if char == '-' else 0
                    flag = 0
                
                elif 0 <= ord(char) - ord('0') < 10:
                    flag = 0
                    num = ord(char) - ord('0')
                else:
                    return 0
            else:
                if 0 <= ord(char) - ord('0') < 10:
                    num = num * 10 + ord(char) - ord('0')
                else:
                    break
        ret = -num if sign else num
        maxint = pow(2, 31) -1
        minint = -pow(2, 31)
        if ret > maxint:
            return maxint
        elif ret < minint:
            return minint
        else:
            return ret

273. Integer to English Words

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1.

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

题目解析:

这一题难度是hard,但是并不难做。2^31是四十多亿,从右向左将数字三个为一组,读出这个1-3位数(不超过1000),然后在后面加上’单位‘,单位依次是 ‘’, ‘thousand’, ‘million', 'billion';基本原理是这样。

还有许多细节问题,一是十几(eleven等),十位数为1时单独处理,二是拼接各部分时空格连接的逻辑,我也没完全处理好。代码如下,可以看出最难写的read这一模块:

class Solution:
    def numberToWords(self, num):
        """
        :type num: int
        :rtype: str
        """
        end = ["", "Thousand", "Million", "Billion", ]
        dig1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
        dig2 = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
        dig3 = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
        def get_read(num):
            num, m = divmod(num, 10)   # m 个位数
            num, n = divmod(num, 10)   # n 十位数 
            
            if num:
                string = dig1[num] + " Hundred"
            else:
                string = ""
            if n == 0:
                if m == 0:
                    pass
                else:
                    if string:
                        string = string + ' ' + dig1[m]
                    else:
                        string += dig1[m]
            elif n == 1:
                if string:
                    string = string + ' ' + dig3[m]
                else:
                    string += dig3[m]                    
            else:
                if string:
                    string = string + ' ' + dig2[n] + ' ' + dig1[m]
                else:
                    string += dig2[n] + ' ' + dig1[m]
                        
            return string.strip()          
                        
        if num == 0:
            return "Zero"
        l = len(str(num))
        div = 1000
        ret = ""
        
        cn = -1
        while num:
            num, m = divmod(num, div)
            cn += 1
            if not m:
                continue
            read = get_read(m)            
            ret = read +' '+ end[cn] + ' ' + ret
            
        
        return ret.strip()

欧克,对于字符串的一些基本的解析/处理的题目就到此了。后面会有更多有主题/有算法思想应用的题目。

猜你喜欢

转载自blog.csdn.net/xutiantian1412/article/details/83036937