The code golf series seem to be fairly popular. I ran across some code that converts a number to its word representation. Some examples would be (powers of 2 for programming fun):
- 2 -> Two
- 1024 -> One Thousand Twenty Four
- 1048576 -> One Million Forty Eight Thousand Five Hundred Seventy Six
The algorithm my co-worker came up was almost two hundred lines long. Seems like there would be a more concise way to do it.
Current guidelines:
- Submissions in any programming language welcome (I apologize to PhiLho for the initial lack of clarity on this one)
- Max input of 2^64 (see following link for words, thanks mmeyers)
- Short scale with English output preferred, but any algorithm is welcome. Just comment along with the programming language as to the method used.
C++, 15 lines:
Usage:
See recursive's better answer. It's way betterer.
Mad props to Darius for inspiration on this one. Your big-
W
(now myp
) was especially clever.I test it with this:
At this point, this is a tweak of Darius' current solution, which is in turn a tweak of my older one, which was inspired by his, and he gave some bug hints in the comments. It is also a crime against Python.
Spoilers below, rot13'd for your protection, because half the fun of golf figuring out how. I highly recommend the mnenhy Firefox extension to decode this (and other simple encoding schemes) inline.
Pbafgnagf (V eranzrq gurz guvf erivfvba gb ubcrshyyl znxr gurz pyrnere.)
R
: Gur rzcgl frg.E
: Gung juvpu vf va pbzzba orgjrra pbhagvat va gur "grraf" (egrra, svsgrra, fvkgrra...) naq va gur graf (egl, svsgl, fvkgl....)Z
,P
: Jung gurl ner va Ebzna ahzrenyf.M
: Nyy gur ahzoref sebz bar gb gjragl.Shapgvbaf (fbzr nyfb eranzrq guvf ebhaq)
j
: Gur choyvp-snpvat shapgvba, juvpu gheaf n ahzore vagb jbeqf._
: Erphefviryl gheaf gur ahzore vagb jbeqf, gubhfnaq-ol-gubhfnaq.a
vf gur ahzore,y
vf ubj sne guebhtu gur cbjref bs 1000 jr ner. Ergheaf n yvfg bs fvatyrgba yvfgf bs rnpu jbeq va gur ahzore, r.t.[['bar'],['gubhfnaq'],['gjragl'],['sbhe']]
.c
: sbe rnpu jbeq va gur fcnpr-frcnengrq jbeq yvfgn
, nccraqfo
nf n fhssvk naq chgf gurz rnpu vagb n fvatyrgba yvfg. Sbe rknzcyr,c("z o ge","vyyvba") == [['zvyyvba'],['ovyyvba'],['gevyyvba']]
.Here's one in PHP, from Convert Numbers to Words:
returns
and if you want an even more awesome one that handles commas and numbers up to vigintillion check out zac hesters work at Language Display Functions: