LeetCode:Roman to Integer
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Roman to Integer相关的知识,希望对你有一定的参考价值。
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
1 class Solution { 2 public: 3 int romanToInt(string s) { 4 map<char,int> dict; 5 dict[‘I‘] = 1, dict[‘i‘] = 1; 6 dict[‘V‘] = 5, dict[‘v‘] = 5; 7 dict[‘X‘] = 10, dict[‘x‘] = 10; 8 dict[‘L‘] = 50, dict[‘l‘] = 50; 9 dict[‘C‘] = 100, dict[‘c‘] = 100; 10 dict[‘D‘] = 500, dict[‘d‘] = 500; 11 dict[‘M‘] = 1000, dict[‘m‘] = 1000; 12 13 int sum=0; 14 for(int i=0;i<s.size();i++) 15 { 16 int j=i+1; 17 if(j<s.size()&&dict[s[i]]<dict[s[j]]) 18 { 19 sum+=dict[s[j]]-dict[s[i]]; 20 i=j; 21 } 22 else 23 sum+=dict[s[i]]; 24 } 25 return sum; 26 27 28 } 29 };
以上是关于LeetCode:Roman to Integer的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode] Roman to integer 罗马数字转成整数