AlgoDaily

Convert Number to Words

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Description

Can you convert a number to its text equivalent? This is otherwise known as number spelling.

For example, given 1234, we expect to get "one thousand two hundred and thirty four" back.

Constraints
  • The given number will have <= 100 digits
  • Let n be the number of digits
  • Expected time complexity : O(n)
  • Expected space complexity : O(n)
```js
function numberToWords(n) {
  // convert n to words
  return n;
}
```

Step Two

This problem is deceivingly complicated, so let's take it step and step. Let's use a simple number, like 123 for now.

First, let's convert 123 to a string type to start our operation.

```
123 -> "123"
```

Step Three

Then check if it's zero (because if it is, we can just return "zero").

Next, let's make sure we've defined the building blocks that will make up the final string. They include:

  • units like one, thirteen, etc.
  • tens values like twenty, thirty, etc.
  • scales like thousand, and million

Now we account for the various scales. Most of the scaling levels come up every 3 digits. Using this code block, we can get every 3 digits as chunks.

```
start = string.length;
chunks = [];
while (start > 0) {
	end = start;
	chunks.push(string.slice((start = Math.max(0, start - 3)), end));
}
```

Complexity Of Final Solution

All it does is start from right to left, grabbing every 3 digits and pushing them into a chunks array.

We then adjust for the scale we're at, and make sure we have enough digits to justify that scale.

Now, here's the key. For each chunk, we process it in this manner:

  1. Split it into individual integers ("123" becomes [1, 2, 3])
  2. Add tens word if array item exists
  3. Add 'and' string after units or tens integer (optional)
  4. Add hundreds word if array item exists

Complexity of Final Solution

Let n be the number of digits in the input num. We iterate through the string equivalent of num, and examining 3 digits at a time for O(n) linear time complexity. When converting nums to a string of length n, we have O(n) space complexity.

One Pager Cheat Sheet

One Pager Cheat Sheet

  • You can convert a number to its text equivalent using number spelling in O(n) time and O(n) space complexity, where n is the number of digits and the number of digits must not exceed 100.
  • We can convert the number 123 to a string type to start our operation.
  • We need to define units, tens and scales for building the final string, and then divide the number into chunks of 3 digits to account for different scales.
  • We iterate through num in O(n) linear time, and convert it to a string of length n for O(n) space complexity.
Open interactive view →