This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Java in General and the fly likes two radix solution to convert Roman numerals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "two radix solution to convert Roman numerals" Watch "two radix solution to convert Roman numerals" New topic

two radix solution to convert Roman numerals

Pat Farrell

Joined: Aug 11, 2007
Posts: 4659

OK, this is not really an advanced Java question, its more of an advanced algorithms question.

Everyone knows how to convert to and from Roman numerals from Arabic numbers. Its typically a CS101 topic.

When I was studying for my PhD, one of my commitee members mentioned that the clever way to do the conversion was to notice that Roman numerals have dual radix. While most programmers can think in binary or hex in addition to decimal, each of these has only a single radix (2, 16 or 10).

If you look a the standard converstion table, it looks like:

Notice that the I, X, C, and M are essentially decimal, but the V, L, and C are used for digits near 5. So its nearly a base 10 and base 5 system.

What I never found out was the clever way to use this to have code more elegant than the usual switch statements.

Anybody seen an implementation?
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
I haven't seen it, but I just made this. It seems to qualify, but's not necessarily the most elegant solution:

The parseRoman() method doesn't do any input validation, but the toRoman() method does, since it was simple. The toRoman() method still has several magic numbers in it that could be derived from other things, but it didn't seem necessary to remove them. Unless you want to generalize the solution to handle additional symbols for larger numbers, or other dual-radix systems.
[ September 03, 2007: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: two radix solution to convert Roman numerals
It's not a secret anymore!