Number to Words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <ctime> | |
#include <string> | |
using namespace std; | |
string convert(unsigned long n) { | |
static char *formats[16] = { | |
"", "%s%s%s", "%s%s", "%s%s-%s", | |
"%s hundred", "%s hundred and %s%s", "%s hundred and %s", "%s hundred and %s-%s", | |
"", "%s%s%s %s", "%s%s%s %s", "%s%s-%s %s", | |
"%s hundred %s%s%s", "%s hundred and %s%s %s", "%s hundred and %s%s %s", "%s hundred and %s-%s %s" | |
}; | |
static char *ones[20] = { | |
"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", | |
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" | |
}; | |
static char *tens[10] = {"", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"}; | |
static char *scales[8] = {"", "thousand", "million", "billion", "trillion", "quadrillion", "quitillion", "sextillion"}; | |
if (n == 0) return "zero"; | |
string sections; | |
for (unsigned s = 0; s < 8 && n > 0; s++) { | |
unsigned o = n % 10; n /= 10; | |
unsigned t = n % 10; n /= 10; | |
unsigned h = n % 10; n /= 10; | |
if (t == 1) { | |
o += 10; t = 0; | |
} | |
unsigned f = (s > 0) * 8 + (h > 0) * 4 + (t > 0) * 2 + (o > 0); | |
char section[43]; // 5 + 13 + 7 + 1 + 5 + 1 + 11 = 43 | |
sprintf(section, formats[f], ones[h], tens[t], ones[o], scales[s]); | |
if (sections.length() > 0) { | |
sections.insert(0, ", "); | |
} | |
sections.insert(0, section); | |
} | |
return sections; | |
} | |
int main(int argc, const char *argv[]) { | |
static unsigned long numbers[1000]; | |
static size_t count = 1000; | |
static clock_t start, ticks; | |
for (size_t g = 0; g < count; g++) { | |
srandomdev(); numbers[g] = random(); // Yes, I know I shouldn't seed it every time... | |
} | |
start = clock(); | |
for (size_t i = 0; i < count; i++) { | |
string converted = convert(numbers[i]); | |
printf("%lu = %s\n", numbers[i], converted.c_str()); | |
} | |
ticks = clock() - start; printf("\n%ld clock ticks (%ld avg/num)", ticks, ticks / count); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment