Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
public class Solution {
/*I = 1;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;
*/
public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
int scale = 1000;
char c[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
for(int i=6;i>=0;i-=2) {
int k = num/scale;
if(k==0) {
} else if(k<=3) {
int t = k;
while(t>0) {
sb.append(c[i]);
t--;
}
} else if(k==4) {
sb.append(c[i]).append(c[i+1]);
} else if(k==5) {
sb.append(c[i+1]);
} else if(k<=8) {
sb.append(c[i+1]);
int t = k;
while(t>5) {
sb.append(c[i]);
t--;
}
} else if(k==9) {
sb.append(c[i]).append(c[i+2]);
}
num = num - k * scale;
scale /= 10;
}
return sb.toString();
}
}
public class Solution {
public String intToRoman(int num) {
if (num > 3999 || num < 1) {
// TODO exception
return "";
}
String cs[] = {"I", "V", "X", "L", "C", "D", "M"};
String ret = "";
int sig = 0;
while (num != 0) {
int val = num % 10;
if (val > 0 && val < 4) {
int tmpVal = val;
while (tmpVal > 0) {
ret = cs[sig * 2] + ret;
tmpVal--;
}
} else if (val == 4) {
ret = cs[sig * 2] + cs[sig * 2 + 1] + ret;
} else if (val == 5) {
ret = cs[sig * 2 + 1] + ret;
} else if (val > 5 && val < 9) {
String tmp = "" + cs[sig * 2 + 1];
int tmpVal = val;
while (tmpVal > 5) {
tmp = tmp + cs[sig * 2];
tmpVal--;
}
ret = tmp + ret;
} else if (val == 9) {
ret = cs[sig * 2] + cs[sig * 2 + 2] + ret;
}
num = num / 10;
sig++;
}
return ret;
}
}
没有评论:
发表评论