huimeich / leetcode-solution

0 stars 0 forks source link

Integer to English Words #199

Open huimeich opened 5 years ago

huimeich commented 5 years ago

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

Example 1:

Input: 123 Output: "One Hundred Twenty Three" Example 2:

Input: 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3:

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

Input: 1234567891 Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"

huimeich commented 5 years ago
def read3str(self, num:int) -> str:
    dic = {1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five",
           6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 0: "",
           10: "Ten", 11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen",
           15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen",
           20: "Twenty", 30: "Thirty", 40: "Forty", 50: "Fifty", 60: "Sixty", 70: "Seventy", 80: "Eighty", 90: "Ninety"}
    hundred = int(num / 100)
    ten = int(int((num - hundred * 100) / 10) * 10)
    one = int(num % 10)
    result = ""
    if num in dic:
        return dic[num]
    if hundred > 0:
        result += dic[hundred] + " Hundred"
    if ten > 19:
        if result != "":
            result += " "
        result += dic[ten]
    else:           
        if result != "" and ten+one > 0:
            result += " "
        result += dic[ten+one]
        return result
    if one != 0:          
        if result != "":
            result += " "
        result += dic[one]
    return (result)
def numberToWords(self, num: int) -> str:
    if num == 0:
        return "Zero"
    dic = {0: "", 3: " Thousand", 6: " Million", 9: " Billion"}
    result = ""
    bi = int(num / 10 ** 9)
    if bi > 0:
        result += self.read3str(bi) + dic[9]
        num = int(num % (10 ** 9))
    mi = int(num / 10 ** 6)
    if mi > 0:
        if result != "":
            result += " "
        result += self.read3str(mi) + dic[6]
        num = int(num % (10 ** 6))
    if int(num / 10 ** 3) > 0:
        if result != "":
            result += " "
        result += self.read3str(int(num / 10 ** 3)) + dic[3]
        num = int(num % (10 ** 3))
    if num > 0:
        if result != "":
            result += " "
        result += self.read3str(num)
    return (result)