Skip to content

Instantly share code, notes, and snippets.

@kmbenjel
Last active May 29, 2023 18:32
Show Gist options
  • Save kmbenjel/56fe17b25c421e6c8b524aef0d02a6ce to your computer and use it in GitHub Desktop.
Save kmbenjel/56fe17b25c421e6c8b524aef0d02a6ce to your computer and use it in GitHub Desktop.
My submission to: `Integer to English Words` challenge on LeetCode (Hard)
# frozen_string_literal: true
def three_digit_to_words(num)
ones = %w[zero one two three four five six seven eight nine]
teens = %w[ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen]
tens = %w[ten twenty thirty forty fifty sixty seventy eighty ninety]
words = []
if (num / 100).positive?
words << ones[num / 100].capitalize
words << 'Hundred'
num %= 100
end
if (10..19).include?(num)
i = num % 10
words << teens[i].capitalize
num = 0
end
num >= 20 ? words << tens[num / 10 - 1].capitalize : false
(num % 10).positive? ? words << ones[num % 10].capitalize : false
words
end
def number_to_words(num)
words = []
s = num.to_s.size
if s >= 10
words << three_digit_to_words(num / (10**9))
(num / 10**9).positive? ? words << 'Billion' : false
(num % 10**9).zero? ? (return words.join(' ')) : num %= 10**9
end
if s >= 7
words << three_digit_to_words(num / (10**6))
(num / 10**6).positive? ? words << 'Million' : false
(num % 10**6).zero? ? (return words.join(' ')) : num %= 10**6
end
if s >= 4
words << three_digit_to_words(num / (10**3))
(num / 10**3).positive? ? words << 'Thousand' : false
(num % 10**3).zero? ? (return words.join(' ')) : num %= 10**3
end
words << three_digit_to_words(num) if s.positive?
num.zero? ? 'Zero' : words.flatten.join(' ')
end
# https://leetcode.com/problems/integer-to-english-words/
@kmbenjel
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment