The source of the topichttps://leetcode.com/problems/roman-to-integer/https://leetcode.com/problems/integer-to-roman/
Achieve the reciprocal conversion of Roman numerals and integers. The number size is between [1, 3999].
Roman Numerals
Roman Numeral LettersRoman numerals consist of only 7 letters, each with the following words
Letters |
M |
D |
C |
L |
X |
V |
I |
Represent numbers |
1000 |
500 |
100 |
50 |
10 |
5 |
1 |
Four RulesThe same number ligatures, the number represented is equal to the number of these numbers added. If XXX indicates that 30 small numbers are on the right side of a large number, the number represented is equal to the number of digits added to these numbers, as in the case of the sum of 8 small (limited by I, X, C) on the left of the large number, the number represented is equal to the large number minus the small number: If IV represents 4, draw a horizontal line above a number, indicating that the number increases Value 1000 times times (
since the title only considers the number within 4000, this rule does not need to be considered)。
Five group number ruleI, X, C: can only use 3, if placed on the left of the large number, only 1. V, L, D: Can not be placed on the left of the large number, can only use one. I can only use the left side of V and X. IV means 4, and IX indicates that 9 x can only be placed on the left side of the l,c. XL indicates that XC C can only be used on the left of D and M. CD representation, CM represents 900
AnalysisThere is a point of trouble, that is, the number can be placed on the left or on the right. That makes the logic of the process not so smooth. If you can only put it on the right side, you could use addition directly. If 9 is expressed as IX, and if represented as VIIII, this is OK if the process is added.
For integers to Roman numerals: You can use combined numbers to split so that the program can implement a method of adding. For Roman digital turn integers: The number that needs to be placed on the left of the large number can only be used to determine whether the current letter is plus or minus.
Code
Integer to Roman numerals
string inttoroman (int num) {
if (num <= 0) return "";
string ret = "";
static int number[13] = {1000, 900, M, 100,90, 9, 5, 4, 1};
static string flags[13] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
for (int i = 0; i < && num > 0; i++) {
if (num < number[i]) continue;
cout<< i << "" << Number[i] << "-" <<flags[i] << Endl;
while (Num >= number[i]) {
num-= number[i];
RET + flags[i];
}
return ret;
}
Roman numeral Turn int
int Romantoint (string s) {
int tagval[256];
tagval[' I '] = 1;
tagval[' V '] = 5;
tagval[' X '] = ten;
tagval[' C '] = m;
tagval[' M '] = 1000;
tagval[' L '] = m;
tagval[' D '] =;
int val = 0;
for (int i = 0; i < s.length (); i++) {
if (i+1 >= s.length () | | tagval[s[i+1]] <= tagval[s[i])
val + + tag Val[s[i]];
Else
val-= tagval[s[i]];
}
return val;
}