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 beforeV
(5) andX
(10) to make 4 and 9. -
X
can be placed beforeL
(50) andC
(100) to make 40 and 90. -
C
can be placed beforeD
(500) andM
(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"
真・暴力法
Runtime: 5 ms, faster than 55.25%
class Solution {
public String intToRoman(int num) {
if (num > 3999 || num < 1){
return null;
}
String romanPieces[]={"","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"};
return romanPieces[num/1000+30]+romanPieces[(num/100)%10+20]
+romanPieces[(num/10)%10+10]+romanPieces[num%10];
}
}
伪・暴力法
Runtime: 3 ms, faster than 100.00%
class Solution {
public String intToRoman(int num) {
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] romanPieces = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length; i++) {
while (num >= values[i]) {
num -= values[i];
sb.append(romanPieces[i]);
}
}
return sb.toString();
}
}
正常计算
Runtime: 4 ms, faster than 79.40%
class Solution {
public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
String[] roman = { "I", "V", "X", "L", "C", "D", "M" };
for (int i = 3,digitNum = 0,temp = 1000; i >= 0; i--,temp /= 10) {
digitNum = (num / temp) %10;
switch (digitNum) {
case 9:
sb.append(roman[2 * i]).append(roman[2 * i + 2]);
break;
case 4:
sb.append(roman[2 * i]).append(roman[2 * i + 1]);
break;
default:
if (digitNum >= 5){
sb.append(roman[2 * i + 1]);
}
for (int j = 0; j < digitNum % 5; j++){
sb.append(roman[2 * i]);
}
break;
}
}
return sb.toString();
}
}