Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
This is also a google interview problem!
I = 1 can be subtracted from 5, 10
V = 5
X = 10 can be subtracted from 50, 100
L = 50
C = 100 can be subtracted from 500, 1000
D = 500
M = 1000
3 = III
30 = XXX
4 = IV
9 = IX
IIX wrong
8 = VIII
1999 = IMM wrong
MCMXCIX = 1999
999 = CM XC IX
you can check wiki to get known of the rules.
I do it by dividing and conquer. always get the biggest smaller number to subtract then do the same to the remainings.
public class Solution {
public static String intToRoman(int num) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap h=new HashMap();
h.put(1,'I');
h.put(5,'V');
h.put(10,'X');
h.put(50,'L');
h.put(100,'C');
h.put(500,'D');
h.put(1000,'M');
int a[]={1,5,10,50,100,500,1000};
StringBuilder s=new StringBuilder();
return new String(get(num,s,h,a));
}
public static int search(int a[], int x){
int i=a.length-1;
while(i>=0&&a[i]>x) i--;
return i;
}
public static StringBuilder get(int x,StringBuilder s,HashMap h, int a[]){
if(h.containsKey(x)){s.append(h.get(x)); return s;}
if(x==0) return s;
int c=search(a,x);
if(x<4*a[c]){
if((c&1)==1&&c<6&&a[c+1]-a[c-1]<=x){//this rule is just for 9->IX not VIV
x=x-a[c+1]+a[c-1];//actually I don't understand this rule well
s.append(h.get(a[c-1]));
s.append(h.get(a[c+1]));
}
else if(x<2*a[c]) {
x-=a[c];
s.append(h.get(a[c]));
}
else if(x<3*a[c]){
x-=2*a[c];
s.append(h.get(a[c]));
s.append(h.get(a[c]));}
else if(x>=3*a[c]){
x-=3*a[c];
s.append(h.get(a[c]));
s.append(h.get(a[c]));
s.append(h.get(a[c]));
}
return get(x,s,h,a);
}
else{
x=a[c+1]-x;
if(c>0&&x<=a[c-1]&&((c&1)==1)){
x=a[c-1]-x;
s.append(h.get(a[c-1]));
s.append(h.get(a[c+1]));}
else if(x<=a[c]&&((c&1)==0)){
x=a[c]-x;
s.append(h.get(a[c]));
s.append(h.get(a[c+1]));}
else {s.append(h.get(a[c+1]));}
return get(x,s,h,a);}
}
}