Given a number between 0 and 9999, print the number in English. For example, for the number 123, print ‘one hundred twenty three’.
const ones = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine'
}
const tens = {
9: 'ninety',
8: 'eighty',
7: 'seventy',
6: 'sixty',
5: 'fifty',
4: 'forty',
3: 'thirty',
2: 'twenty',
1: 'ten'
}
let teens = {
19: 'nineteen',
18: 'eighteen',
17: 'seventeen',
16: 'sixteen',
15: 'fifteen',
14: 'fourteen',
13: 'thirteen',
12: 'twelve',
11: 'eleven',
10: 'ten'
}
let number = 123
number = 5
number = 15
number = 21
// number = 113
// number = 4103
// number = 9999
let digitIndex = 0
let remainder = 0
let firstDigit = 0
let sentence = ''
while (number > 0) {
remainder = number % 10
number = parseInt(number / 10, 10)
digitIndex += 1
if (digitIndex === 1) { // 1st digit
firstDigit = remainder
sentence = '' + ones[remainder]
console.log(remainder)
}
else if (digitIndex === 2) { // 2nd digit
if (remainder >= 2) { // 20 and up
if (firstDigit > 0) {
sentence = tens[remainder] + ' ' + sentence
} else {
sentence = tens[remainder]
}
}
else if (remainder === 1) { // teens or ten
const total = 10 + firstDigit
sentence = teens[total]
}
else { // ones
sentence = ones[firstDigit]
}
}
else if (digitIndex === 3) { // 3rd digit
sentence = ones[remainder] + ' hundred ' + sentence
}
else if (digitIndex === 4) { // 4th digit
sentence = ones[remainder] + ' thousand ' + sentence
}
}
console.log(sentence)