1. Description
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
2. Example
input s = "XXIII"
output 23
3. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="C++" active="active"]
int romanToInt(string s) { static unordered_mapmap = { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } }; int sum = map[s.back()]; for (int i = 0; i < s.length() - 1; i++) { sum = map[s[i]] < map[s[i + 1]] ? sum - map[s[i]] : sum + map[s[i]]; } return sum; }
[/restab]
[/restabs]
4.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="C++" active="active"]
#include#include #include using namespace std; class LeetCode13 { public: int romanToInt(string s) { static unordered_map map = { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } }; int sum = map[s.back()]; for (int i = 0; i < s.length() - 1; i++) { sum = map[s[i]] < map[s[i + 1]] ? sum - map[s[i]] : sum + map[s[i]]; } return sum; } }; int main() { LeetCode13 leetCode13; cout << leetCode13.romanToInt("MMMCMXCIX") << endl; system("pause"); return 0; }
[/restab]
[/restabs]
Comments | NOTHING