First, learn about the Roman numerals, refer to the Roman numerals
Roman numerals are the oldest digital representation, more than 2000 years earlier than the Arabic array, originating in Rome
The Roman numerals have the following symbols:
Basic Characters |
I |
V |
X |
L |
C |
D |
M |
Corresponding to Arabic numerals |
1 |
5 |
10 |
50 |
100 |
500 |
1000 |
Counting rule: the same number is written in a row. The number is equal to the sum of the numbers. For example, a number with a size of IIi = 3 is on the right of a large number, the number is equal to the sum of these numbers. For example, if VIII is 8 small numbers, the values (I, X, and c) are on the left side of a large number, the number is equal to the number of digits minus the number of decimal digits. For example, when IV = 4 is used normally, the number of consecutive digits must not exceed three times to draw a horizontal line on the same number, this number is increased by 1000 times (this question only considers the number smaller than 3999, so this rule is not used)
Second, the rules for the conversion of Roman numerals to Arabic numerals (limited to less than 3999 ):
Traverse the roman numerals from the front to the back. If a number is smaller than the previous one, add this number. Otherwise, double the previous number and add this number.
// Romantointeger. cpp: defines the entry point of the console application. // # Include "stdafx. H "# include <map >#include <iostream> using namespace STD; Class solution {public: int romantoint (string s) {Map <char, int> romanmap; romanmap ['I'] = 1; romanmap ['V'] = 5; romanmap ['X'] = 10; romanmap ['l'] = 50; romanmap ['C'] = 100; romanmap ['D'] = 500; romanmap ['M'] = 1000; int sum = 0; For (INT I = 0; I <S. size (); I ++) {if (I = 0) sum + = romanmap [s [I]; else {If (romanmap [s [I] <= romanmap [s [I-1]) sum + = romanmap [s [I]; elsesum + = (romanmap [s [I]-2 * romanmap [s [I-1]) ;}} return sum ;}; int _ tmain (INT argc, _ tchar * argv []) {solution SS; int sum = ss. romantoint ("VIII"); cout <sum <Endl; System ("pause"); Return 0 ;}
[Leetcode] Roman to integer