七个罗马字母:I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、M(1000)
规则:
(1)小的数字放右边表示相加,且V、 L、 D只能用一次;
(2)小的(只限于I、X、C)放左边表示减去小的,且只能用一个;
(3)连写不能超过3次;
(4)在一个数上划横线,表示这个数增值1000倍。
1.将十进制数(0-3999)转换成罗马数字
public class Solution{ public static void main(String[] args){ System.out.PRintln(intToRoman(2344)); } private static String intToRoman(int num) { String[][] c = new String[][]{ {"","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"} }; String roman = ""; roman += "" + (c[3][num / 1000 % 10]); roman += "" + (c[2][num / 100 % 10]); roman += "" + (c[1][num / 10 % 10]); roman += "" + (c[0][num % 10]); return roman; }}2.将罗马数字转换成十进制数(0-3999)public class Solution { public int romanToInt(String s) { Map<Character, Integer> map = new HashMap<Character, Integer>(); map.put('I', 1); map.put('V', 5); map.put('X', 10); map.put('L', 50); map.put('C', 100); map.put('D', 500); map.put('M', 1000); int length = s.length(); int result = map.get(s.charAt(length - 1)); for(int i = length - 1; i > 0; i--){ if(map.get(s.charAt(i)) > map.get(s.charAt(i-1))){ result -= map.get(s.charAt(i-1)); }else{ result += map.get(s.charAt(i-1)); } } return result; }}罗马数字的记法:
I,II,III表示手指的根数(1,2,3),一只手为V(5),两只手为X(两个V,即10),一百(一个世纪Century)为C,C的一半为L(即50),一千为M(Mille拉丁文里的一千,和Mile很像),D为500单独记。
新闻热点
疑难解答