Teaser Image

# qnoid

## Markos Charatzas - London, UK

Just recently came across this case needing to convert a number to its wording. For example, given the number 27 produce "twentyseven".

One way to tackle this is to dissect the number to its digits one by one, starting by the lower ones.

``````(0)         2       7
(hundreds)  tens    units
``````

Using a lookup table on units, tens, hundreds will allow us to get the wording for a single number.

The real question then becomes, what algorithm will give us the number of the right magnitude? In other words, how can we get the units, the tens and the hundreds of a number?

For that we will take advantage of the mod operator with a touch of recursion to traverse the whole number.

First a reminder on the mod. Whenever you mod a number, the value you get back is anywhere within the range of the modulo, starting from 0.

e.g.

``````27 % 10     =   7   (units)
20 % 100    =   20  (tens)
0  % 1000   =   0   (hundreds)
``````

With that in mind, starting from 10 as the modulo we get the value of the units, thus its wording.

Every time subtracting the current value from the number to be left with the next scale.

``````27 - 7 = 20
``````

and modding again with the next modulo

``````mod * 10
``````

until we get a 0 as the number, which is the stop condition.

What about numbers that are missing digits like 100 which will give a 0 as soon as we mod them? Well, there are a couple of ways to go about it.

• Add a lookup value of an empty string to 0. This although works, breaks the semantics of the lookup.

• Check for a null and use an empty string instead. In this case you will have the overhead of allocating the StringBuilder and that of the append.