搜索此博客

2012年8月27日星期一

Integer To Roman

We first see the integer to roman problem, the solution of which is quite straightforward.

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
The rules of conversion can be seen in Wikipedia.
http://en.wikipedia.org/wiki/Roman_numerals

Basically, we only have several characters
I (1), V (5)
X (10), L (50)
C (100), D (500)
M (1000)
Therefore, we can represent several groups of numbers in several arrays. These groups will compose the result.
Group 1: 1-9
Group 2: 10-90
Group 3: 100-900
Group 4: 1000-3000

Now, we have this solution in our mind, and the code is easy to write:

01 public String intToRoman(int num) {      
02     String[]digits={"I","II","III","IV","V","VI","VII","VIII","IX"};
03     String[]tens={"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
04     String[]hundreds={"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
05     String[]thousands={"M","MM","MMM"};
06   
07     StringBuffer sb=new StringBuffer();
08     int value;
09   
10     value=num/1000;
11     if(value>0)
12     {
13         sb.append(thousands[value-1]);
14     }
15   
16     num=num%1000;
17     value=num/100;      
18     if(value>0)
19     {
20        sb.append(hundreds[value-1]);
21     }
22   
23     num=num%100;      
24     value=num/10;
25     if(value>0)
26     {
27        sb.append(tens[value-1]);
28     }
29   
30     num=num%10;
31     if(num>0)
32     {
33         sb.append(digits[num-1]);
34     }
35   
36     return sb.toString();
37 }

没有评论:

发表评论