Last active
August 29, 2015 13:57
-
-
Save jayrobin/9631274 to your computer and use it in GitHub Desktop.
Prompts for a number and outputs the same number in English
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# convert a triplet (0-999) into english words representing the value | |
def triplet_to_words(triplet) | |
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] | |
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] | |
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] | |
left_digit = triplet / 100 | |
middle_digit = (triplet % 100) / 10 | |
right_digit = triplet % 10 | |
word = "" | |
word << "#{ones[left_digit]} hundred " if left_digit > 0 | |
word << "#{teens[right_digit]} " if middle_digit == 1 | |
word << "#{tens[middle_digit]} " if middle_digit > 1 | |
word << "#{ones[right_digit]} " unless middle_digit == 1 | |
word | |
end | |
# converts any number into english words representing the value | |
def number_to_words(number, magnitude = 0) | |
return "" if number == 0 # base case | |
illions = ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion"] | |
word = "" | |
word << number_to_words(number / 1000, magnitude + 1) if number > 1000 | |
word << triplet_to_words(number % 1000) | |
word << "#{illions[magnitude]} " if magnitude > 0 | |
word | |
end | |
print "Enter a number: " | |
number = gets.chomp.to_i | |
puts number_to_words(number) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment