1 题目要求:
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"
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.
2 解决方法:
题目挺无聊,简单粗暴
const int x=[](){
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
class Solution {
public:
string intToRoman(int num) {
int One_num = num % 10; num /= 10;
int Ten_num = num % 10; num /= 10;
int Hundred_num = num % 10; num /= 10;
const int Thousand_num = num % 10;
string ret;
string Thousand_str(Thousand_num, 'M');
ret.append(Thousand_str);
switch (Hundred_num) {
case 1: ret.append("C"); break;
case 2: ret.append("CC"); break;
case 3: ret.append("CCC"); break;
case 4: ret.append("CD"); break;
case 5: ret.append("D"); break;
case 6: ret.append("DC"); break;
case 7: ret.append("DCC"); break;
case 8: ret.append("DCCC"); break;
case 9: ret.append("CM");
}
switch (Ten_num) {
case 1: ret.append("X"); break;
case 2: ret.append("XX"); break;
case 3: ret.append("XXX"); break;
case 4: ret.append("XL"); break;
case 5: ret.append("L"); break;
case 6: ret.append("LX"); break;
case 7: ret.append("LXX"); break;
case 8: ret.append("LXXX"); break;
case 9: ret.append("XC");
}
switch (One_num) {
case 1: ret.append("I"); break;
case 2: ret.append("II"); break;
case 3: ret.append("III"); break;
case 4: ret.append("IV"); break;
case 5: ret.append("V"); break;
case 6: ret.append("VI"); break;
case 7: ret.append("VII"); break;
case 8: ret.append("VIII"); break;
case 9: ret.append("IX");
}
return ret;
}
};
或者用数组少些一点
public static String intToRoman(int num) {
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"};
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}
题目很无聊,复习了一下switch。