Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/fea9b0534062372d3e66925755f57a92 to your computer and use it in GitHub Desktop.
Save jianminchen/fea9b0534062372d3e66925755f57a92 to your computer and use it in GitHub Desktop.
Leetcode 273 - Integer to English words - review the peer's JavaScript code
/*
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1.
For example,
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
less than 2 billion ->
*/
const upToTwenty = ['', "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten","Eleven",
"Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
const tens = ['', "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
const thousands = ['', 'Thousand', 'Million', 'Billion'];
function numToWords(num) {
// convert the input number to a string
// if the number is bigger than 12 places
// return 0 it would be too big
if (num.toString().length > 12) return 'TOO BIG';
if (num === 0) {
return 0;
}
let counter = 0;
// crete a results string ''
let res = '';
// We have strings representations
// while the number is > 0
while (num > 0) {
// the number is % 1000 not 0
// set out results sting equal to helper(current Num%1000) + counter a res
if (num % 1000 !== 0) {
res = `${getNums(num%1000)} ${thousands[counter]} ${res}`;
}
// num = num/1000
// counter++
num = Math.floor(num / 1000);
counter++;
}
return res;
}
const getNums = number => {
// if the number is 0
// return '';
if (number === 0) {
return '';
}
else if (number < 20) {
return upToTwenty[number];
}
else if (number < 100) {
return `${tens[Math.floor(number/10)]} ${getNums(number % 10)}`;
}
else {
return `${upToTwenty[Math.floor(number/100)]} Hundred ${getNums(number%100)}`;
}
// if the number is less than 20
// return upToTwenty[number]
// else if the number is < 100
// return floor this number tens[number/10] + getNums(number % 10)
// This case should handle hundreds
// return floor upToTwenty[num/100] + hundreds getnums(number%100)
}
let testNum = 1234 *5678 * 9000
let result = numToWords(testNum);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment