Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
* I can be placed before V (5) and X (10) to make 4 and 9.
* X can be placed before L (50) and C (100) to make 40 and 90.
* C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
1.Roman to Integer
难点在于IV这种要怎么做。其实观察顺序即可,正常来说都应该base应该从大到小,如果忽然有小在前比如IV,那就看做-10+50。所以按顺序扫下去,每个字符和下一个字符对比大小,如果大一些即+,如果是小一些即-。
2.Integer to Roman
数位分离 / %。利用/可以知道比如要几个M。利用%可以知道把M都去掉后剩下来要给后面的小base处理的数是多少。
一开始那片常数定义类似于:String[] I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX”};
细节:数位分离可以应用于把十进制数转为任意进制数。但原始数据不能非十进制数,因为我们计算机里的/ %实现是针对十进制数的。
1.Roman to Integer实现
class Solution { public int romanToInt(String s) { if (s == null || s.length() == 0) { return 0; } int[] map = new int[256]; map['I'] = 1; map['V'] = 5; map['X'] = 10; map['L'] = 50; map['C'] = 100; map['D'] = 500; map['M'] = 1000; int sum = 0; for (int i = 0; i < s.length() - 1; i++) { if (map[s.charAt(i + 1)] > map[s.charAt(i)]) { sum -= map[s.charAt(i)]; } else { sum += map[s.charAt(i)]; } } sum += map[s.charAt(s.length() - 1)]; return sum; } }
2.Integer to Roman 实现
class Solution { public String intToRoman(int num) { if (num < 0 || num > 3999) { return ""; } String[] M = {"", "M", "MM", "MMM"}; String[] C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; String[] X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; String[] I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; String ans = ""; ans += M[num / 1000]; num %= 1000; ans += C[num / 100]; num %= 100; ans += X[num / 10]; num %= 10; ans += I[num]; return ans; } }