题目
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 an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: 3
Output: “III”
Example 2:
Input: 4
Output: “IV”
Example 3:
Input: 9
Output: “IX”
Example 4:
Input: 58
Output: “LVIII”
Explanation: L = 50, V = 5, III = 3.
Example 5:
Input: 1994
Output: “MCMXCIV”
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
罗马字符 | M | D | C | L | X | V | I |
---|---|---|---|---|---|---|---|
对应数字 | 1000 | 500 | 100 | 50 | 10 | 5 | 1 |
可以举一些例子来发现规律
100 -> C
200 -> CC
300 -> CCC
400 -> CD
500 -> D
600 ->DC
700 -> DCC
800 -> DCCC
900 -> CM
因为D(500)、L(50)、V(5) 他们本身并不能放在比他们大的数的左边或右边 来表示对应的减或加。可以认为只是用来"简化"、"辅助"的。
如:D(500)、C(100)、L(50)
CCCC --> CD
CCCCC --> D
这道题所表示的数字的范围为[1 - 3999]
可以依次除1000,100,10,还要记得取余,得到对应位数的数字。
根据得到的值,可以分为几种情况:
1-3:只需重复对应次数(eg:300 -> CCC)
100 -> C
200 -> CC
300 -> CCC
4: 这个字符(对应的 千位、百位、个位)+ 上一个字符(用来简化对应的位的)
400 -> CD
5-8:上一个字符 + 这个字符(减去5的值则是对应重复的次数)
500 -> D
600 ->DC
700 -> DCC
800 -> DCCC
9:这个字符 + 前两个字符
900 -> CM
java 代码
public String intToRoman(int num) {
String result = "";
char[] roman = {'M','D','C','L','X','V','I'};
int[] value = {1000,500,100,50,10,5,1};
for(int i = 0; i < 7; i += 2) {
int t = num / value[i];
if(t < 4) {
for(int j = 0; j < t; j++) result += roman[i];
}else if(t == 4) {
result = result + roman[i] + roman[i-1];
}else if(t > 4 && t < 9) {
result = result + roman[i-1];
for(int j = 0; j < t - 5; j++) result = result + roman[i];
}else if(t == 9) {
result = result + roman[i] + roman[i-2];
}
num %= value[i];
}
return result;