Integer to English Words Hard 0 attempts
LeetCode ↗

Integer to English Words

Hard StringHash Table LeetCode

Convert a non-negative integer num to its English words representation. Handle numbers from 0 up to 2^31 - 1. The words should follow standard English conventions: groupings of Billion, Million, Thousand, and combinations of Hundred with Tens and Ones.

Example 1:

Input: num = 123
Output: "One Hundred Twenty Three"

Example 2:

Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"
Sample Input
Sample Output
Constraints
  • 0 <= num <= 2^31 - 1
Test Cases
Case 1
Args: [123] Expected: "One Hundred Twenty Three"
Case 2
Args: [0] Expected: "Zero"

Chunk by Thousands

function numberToWords(num) {
  if (num === 0) return "Zero";
  const ones = ['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine',
    'Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen'];
  const tens = ['','','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety'];
  const thousands = ['','Thousand','Million','Billion'];
  function helper(n) {
    if (n === 0) return '';
    if (n < 20) return ones[n] + ' ';
    if (n < 100) return tens[Math.floor(n/10)] + ' ' + helper(n%10);
    return ones[Math.floor(n/100)] + ' Hundred ' + helper(n%100);
  }
  let result = '', i = 0;
  while (num > 0) {
    if (num % 1000 !== 0) result = helper(num % 1000) + thousands[i] + ' ' + result;
    num = Math.floor(num / 1000); i++;
  }
  return result.trim();
}

Time: O(1) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript