Leetcode | Roman to Integer
Problem:
Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.
Convert the roman numerals into integers.
Thinking:
(1) Roman numerals:
There are 7 roman numerals, namely I (1), V (5), X (10), L (50), C (100), D (500) and M (1000 ). Any positive integer can be expressed according to the following rules. It should be noted that there is no "0" in the number of Rome, and it has nothing to do with the carry system. Generally, it is assumed that a number in Rome is only used for counting, rather than computing.
Repeat several times: If a roman number is repeated several times, it indicates several times the number.
Add right minus:
On the right side of a large number, remember a small number to indicate a large number and a small number.
On the left side of a large roman number, a small roman number is displayed, indicating that a large number reduces the number.
There is a limit on the number to be subtracted from the left, which is limited to I, X, and C. For example, 45 cannot be written as VL, but XLV
However, a single digit cannot be exceeded when you subtract the value from the left. For example, 99 cannot be represented by IC (100-1), but XCIX ([100-10] + [10-1. (Equivalent to each Arabic digit .)
The left minus number must be one digit. For example, 8 is written as VIII, not IIX.
The right-plus number cannot exceed three consecutive digits. For example, 14 is written as XIV rather than XIIII. (See "Digital restrictions" below .)
Add a line by thousands:
Add a horizontal line or a lower mark to the top of the Roman numerals ?, This number is multiplied by 1000, Which is 1000 times the original number.
Similarly, if there are two crosslines above, that is, 1000000 (1000 ^ {2}) times of the original number.
Digital restrictions:
The same number can only appear three times at most, for example, 40 cannot be expressed as XXXX, but XL.
Exception: Because IV is the first character of the ancient Rome mythical master God Zhu Pite (that is, IVPITER, there is no J and U in the ancient Rome letters), it is sometimes used to replace IV with IIII.
Code:
class Solution {public: int romanToInt(string s) { // Note: The Solution object is instantiated only once and is reused by each test case. int result=0; map
roman; roman['I']=1; roman['V']=5; roman['X']=10; roman['L']=50; roman['C']=100; roman['D']=500; roman['M']=1000; for(int i=s.length()-1;i>=0;i--) { if(i==s.length()-1) { result=roman[s[i]]; continue; } if(roman[s[i]] >= roman[s[i+1]]) result+=roman[s[i]]; else result-=roman[s[i]]; } return result; }};