题目出处
https://leetcode.com/problems/integer-to-roman/
思路:对于整数转罗马数字:可以使用组合数字来进行拆分,使程序能够实现连加的方法。
对于罗马数字转整数: 需要得用放在大数左边的数字只能使用一个的特点来判断对当前字母是加还是减。
/**
* Created by a819 on 2017/8/7.
*/
public class RomanToInt {
public int getValue(char c) {
switch (c) {
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;
default:return 0;
}
}
public int romanToInt(String s) {
int result=0;
if (s.length()<1)
return 0;
for(int i=0;i<s.length();i++){
char lc=s.charAt(i);
//char rc=s.charAt(i+1);
if(i+1>=s.length()||getValue(lc)>=getValue(s.charAt(i+1)))
result+=getValue(lc);
else
result-=getValue(lc);//如果当前字符代表的数字小于右边的数字,则应该减去
}
return result;
}
/*
public static void main(String[] args) {
RomanToInt ro=new RomanToInt();
String s="MCCLIX";
System.out.println(ro.romanToInt(s));
}
*/
}
/**
* Created by a819 on 2017/8/7.
*/
public class intTOROman {
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 d=0;
while(num!=0)
{
int temp=num%10;
result=roman[d][temp]+result;
d++;
num/=10;
}
return result;
}
public static void main(String[] args) {
intTOROman a=new intTOROman();
int num=1259;
System.out.println(a.intToRoman(num));
}
}
部分内容转自http://blog.csdn.net/net_wolf_007/article/details/51770112
http://www.cnblogs.com/masterlibin/p/5531399.html