1、wiki:Roman数字介绍
https://en.wikipedia.org/wiki/Roman_numerals
2、
Symbol | Value |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
3、
Combination | Value |
---|---|
IV | 4 |
IX | 9 |
XL | 40 |
XC | 90 |
CD | 400 |
CM | 900 |
4、代码
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int romanToInt(string s)
{
if(s.length() < 1) return 0;
int pre = 0;
int cur = 0;
int result = getNumValue(s[0]);
for(int i = 1; i < s.length(); ++i)
{
pre = getNumValue(s[i-1]);
cur = getNumValue(s[i]);
if(cur <= pre)
result += cur;
else
result = cur - 2*pre + result;
}
return result;
}
int getNumValue(char c)
{
switch (c)
{
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
};
int main()
{
Solution s;
cout << "DCXXI: " << s.romanToInt("DCXXI") << endl;
cout << "MCMXCVI: " << s.romanToInt("MCMXCVI") << endl;
}