Skip to problem
←

Integer to English Words

Hard 0 attempts

Convert the nonnegative integer num to English number words using Billion, Million, Thousand, and Hundred groups. Skip groups whose value is zero.

Capitalize each word and use exactly one space between words. Do not include “and”, hyphens, or punctuation. For example, 1001 becomes "One Thousand One", not "One Thousand and One". The number 0 becomes "Zero".

Function contract

num is an integer from 0 through 2147483647.

Output: Return title-cased English number words separated by single spaces, with no leading/trailing spaces, commas, hyphens, or “and”. Return “Zero” for 0.

Example 1

Input
num = 123
Output
"One Hundred Twenty Three"

Example 2

Input
num = 0
Output
"Zero"
Constraints
  • 0 <= num <= 2^31 - 1
Topics

Chunk by Thousands

javascript
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) for the fixed 32-bit input range, which has at most four three-digit groups.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript