Skip to content

273. Integer to English Words #80

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
tech-cow opened this issue Feb 9, 2020 · 0 comments
Open

273. Integer to English Words #80

tech-cow opened this issue Feb 9, 2020 · 0 comments

Comments

@tech-cow
Copy link
Owner

tech-cow commented Feb 9, 2020

'''
[8:41] Start

Thoughts (Didn't execute since not sure?):
    Use a stack, and looking @ elements from the end
    Having a hashmap
        {
            key                      |       val
            reverse index of input   |    assoicated english words (ex: "hundred", "thousand")
        }
    manually input some logic around index
    
    
        
[8:44] a bit cancer, give up | Solution Checking & retrospect

[8:44 - 10:52] Eat, Shower, think about this shit, and having brain fart but finally crack it

[10:53] Start Coding again

Problem Soving:
    1. digits rules : name changes every thousands
        1,000,000,000
        b   m   t

    2. Using divide and conquer to continue breaking large number to smaller instance
        and have a few base case to handle any numbers smaller than hundreds
      
[11:41] FUCK it, so many edge case... why?
'''

# dfs: make sure to keep track of parameter passing 
class Solution(object):
    def numberToWords(self, num):
        less_than_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"]
        tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
        thousands = ["" , "Thousand", "Million", "Billion"]

        res = ""
        if num == 0: return "Zero"
        for i in range(len(thousands)):
            if num % 1000 != 0:
                res = self.dfsHelper(num % 1000, less_than_20, tens).strip() + " " +  thousands[i] + " " + res
            num //= 1000
        return res.strip()

    def dfsHelper(self, num, less_than_20, tens):
        if num < 20:
           return less_than_20[num] 
        elif 20 <= num < 100:
            return tens[num // 10] + " " + less_than_20[num % 10]
        elif 100 <= num <= 999:
            return less_than_20[num // 100] + " Hundred " + self.dfsHelper(num % 100, less_than_20, tens)
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant