题目:Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999
中文意思就是,将罗马数字转换成整数。
解题思路:首先要了解罗马数字是怎样表示数的。这里借助百度百科的相关知识。
罗马数字是阿拉伯数字传入之前使用的一种数码。罗马数字采用七个罗马字母作数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。记数的方法:
-
1、相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
-
2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
-
3、小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;
了解了之后,按照这些规则即可写出转换的代码。我的写法是,先将所有字母代表的数相加,然后再减去符合第3个计数方法的数值。
代码如下:
using namespace std;
class Solution {
public:
int romanToInt(string s) {
int sum = 0;
for (int i = 0 ; i < s.length(); i++) {
char former = s[i];
char batter = 0;
if (i > 0)
batter = s[i-1];
if (former == 'M') {
sum = sum+1000;
if (batter == 'C')
sum = sum-200;
}
if (former == 'D') {
sum = sum+500;
if (batter == 'C')
sum = sum-200;
}
if (former == 'C') {
sum = sum+100;
if (batter == 'X')
sum = sum-20;
}
if (former == 'L') {
sum = sum+50;
if (batter == 'X')
sum = sum-20;
}
if (former == 'X') {
sum = sum+10;
if (batter == 'I')
sum = sum-2;
}
if (former == 'V') {
sum = sum+5;
if (batter == 'I')
sum = sum-2;
}
if (former == 'I')
sum = sum+1;
}
return sum;
}
};
class Solution {
public:
int romanToInt(string s) {
int sum = 0;
for (int i = 0 ; i < s.length(); i++) {
char former = s[i];
char batter = 0;
if (i > 0)
batter = s[i-1];
if (former == 'M') {
sum = sum+1000;
if (batter == 'C')
sum = sum-200;
}
if (former == 'D') {
sum = sum+500;
if (batter == 'C')
sum = sum-200;
}
if (former == 'C') {
sum = sum+100;
if (batter == 'X')
sum = sum-20;
}
if (former == 'L') {
sum = sum+50;
if (batter == 'X')
sum = sum-20;
}
if (former == 'X') {
sum = sum+10;
if (batter == 'I')
sum = sum-2;
}
if (former == 'V') {
sum = sum+5;
if (batter == 'I')
sum = sum-2;
}
if (former == 'I')
sum = sum+1;
}
return sum;
}
};