参考:http://blog.csdn.net/ljiabin/article/details/39968583
1、罗马字母与数值的对应关系,罗马数字的范围0~3999
int toNumber(char ch) {
switch (ch) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
}
return 0;
}
2、CDL ==>550
转化方式:从右往左,如果左值比右值小,则减;如果左值比右值大,则加
public int romanToInt(String s) {
char[] array=s.toCharArray();
int result=toNumber(array[array.length-1]);
for(int i=array.length-2;i>=0;i--){
int t2=toNumber(array[i+1]);
int t1=toNumber(array[i]);
if(t1>=t2){
result+=t1;
}
else{
result-=t1;
}
}
return result;
}
3、转化方式:数值每个位置的数都表示一个罗马数字,如69(LXIX),其中LX和IX分别表示60和9.
roman的数组,表示{1,2,3,。。。10,20,30.。。。100,200,300.。。}
public String intToRoman(int num) {
String result="";
String[][] roman={
{"","I","II","III","IV","V","VI","VII","VIII","IX"},
{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
{"","M","MM","MMM"}
};
int col=0;
while(num!=0){
int remain=num%10;
result=roman[col][remain]+result;
col++;
num=num/10;
}
return result;
}
还有一种暴力方式:
class Solution {
public:
string intToRoman(int num) {
string str;
string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int value[]= {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
for(int i=0;num!=0;++i)
{
while(num>=value[i])
{
num-=value[i];
str+=symbol[i];
}
}
return str;
}
};