Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题目要求把罗马数字转换为阿拉伯数字,这个题很简单,只不过代码量比较大
先查查维基百科罗马数字的知识,各个字母分别代表什么意思
Symbol | Value |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1,000 |
- I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten)
- X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a hundred)
- C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)[5]
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Solution {
public int romanToInt(String s) {
int num = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'C') {
if ((i + 1 < s.length()) && s.charAt(i + 1) == 'M') {
num += 900;
i++;
} else if ((i + 1 < s.length()) && s.charAt(i + 1) == 'D') {
num += 400;
i++;
} else {
num += 100;
}
} else if (s.charAt(i) == 'X') {
if ((i + 1 < s.length()) && s.charAt(i + 1) == 'C') {
num += 90;
i++;
} else if ((i + 1 < s.length()) && s.charAt(i + 1) == 'L') {
num += 40;
i++;
} else {
num += 10;
}
} else if (s.charAt(i) == 'I') {
if((i + 1 < s.length()) && s.charAt(i + 1) == 'X') {
num += 9;
i++;
} else if ((i + 1 < s.length()) && s.charAt(i + 1) == 'V') {
num += 4;
i++;
} else {
num += 1;
}
} else if (s.charAt(i) == 'M') {
num += 1000;
} else if (s.charAt(i) == 'D') {
num += 500;
} else if (s.charAt(i) == 'L') {
num += 50;
} else if (s.charAt(i) == 'V') {
num += 5;
}
}
return num;
}
}