Thursday, July 06, 2006

Decimal to Roman

Write a function to convert a number to its equivalent roman numeral value. You have to convert only numbers < 1000. Analyze the runtime. (This was really hard, and I fluffed my way through it.)


char* u2roman(unsigned n)
{
static char* roman_digits[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
static char* roman_tenths[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
static char* roman_hundreds[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
static char buf[13]; // Max length is 12 symbols
int cnt;

if (n >= 1000) return 0;

cnt = sprintf(buf, "%s", roman_hundreds[ n / 100 ]);
cnt += sprintf(buf + cnt, "%s", roman_tenths[ n / 10 ]);
sprintf(buf + cnt, "%s", roman_digits[ n % 10 ]);

return buf;
}

1 comment:

Anonymous said...

it doesn't work for 100 .. but excellent idea ! ..