13. Roman to Integer
原题:
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 before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
翻译:
罗马数字由七个不同的符号表示: I, V, X, L, C, D and M.
标识 数
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
举个例子, 2在罗马数字里面表示为II. 12表示为XII, 就是 X + II. 27写作XXVII, 就是 XX + V + II.
罗马数字通常采用从左到右从最大到最小的写法. 然而4不是由IIII表示. 而是用IV表示. 因为I在V的前面 V-I得到4.同样的理论可以用于9, 写作IX. 以下是六个使用减法的实例:
I 可以在 V (5) 和X (10)前面表示 4 和 9.
X 可以在 (50) 和 C (100) 前面表示 40 和 90.
C 可以在 D (500) 和 M (1000) 前面表示 和 900.
给出一个罗马数字转化为对应的十进制数. 输入保证在1到3999之间
例 1:
Input: "III"
Output: 3
例 2:
Input: "IV"
Output: 4
例 3:
Input: "IX"
Output: 9
例 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
例 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
C++程序
class Solution {
public:
char r[7]={'I','V','X','L','C','D','M'};
int n[7]={1,5,10,50,100,500,1000};
int romanToInt(string s) {
int num=0;
for(int j=0;j<s.length();j++)
{
int lastnum=0;
int i=0;
for(i=0;i<8;i++)
{
if(s[j]==r[i])break;
}
if(j>0)
for(lastnum=0;lastnum<8;lastnum++)
{
if(s[j-1]==r[lastnum])break;
}
if((i>0) && (n[lastnum]<n[i])&& (j>0))
{
num=num-n[lastnum]*2;
}
num=num+n[i];
}
return num;
}
};