From fec032985abdf5c864ab35493678346f186f3630 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Tue, 6 Aug 2024 18:40:25 -0600 Subject: 273. integer to english words --- integer_english_words.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 integer_english_words.py (limited to 'integer_english_words.py') diff --git a/integer_english_words.py b/integer_english_words.py new file mode 100644 index 0000000..e8f817a --- /dev/null +++ b/integer_english_words.py @@ -0,0 +1,39 @@ +# 273. Integer to English Words + +""" +convert a non-negative integer 'num' to its english words represetation. +""" + + +class Solution(object): + def numberToWords(self, num): + """ + :type num: int + :rtype: str + """ + + below_twenty = ( + "One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve " + "Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen".split() + ) + tens = "Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety".split() + + def words(n): + if n < 20: + return below_twenty[n - 1 : n] + if n < 100: + return [tens[n / 10 - 2]] + words(n % 10) + if n < 1000: + return [below_twenty[n / 100 - 1]] + ["Hundred"] + words(n % 100) + for p, w in enumerate(("Thousand", "Million", "Billion"), 1): + if n < 1000 ** (p + 1): + return words(n / 1000**p) + [w] + words(n % 1000**p) + + return " ".join(words(num)) or "Zero" + + +if __name__ == "__main__": + obj = Solution() + print(obj.numberToWords(123)) + print(obj.numberToWords(12345)) + print(obj.numberToWords(1234567)) -- cgit v1.2.3