Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
| 基本字符 | I | V | X | L | C | D | M |
| 对应阿拉伯数字 | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
同时,这里也用到了STL中map<char,int>,如果小伙伴们知道怎么用,这道题就不怎么难了,当时我也不知道该如何下手,看了别人的思路,豁然开朗。
class Solution { public: int romanToInt(string s) { int nLength=s.length(); if(nLength<1) return 0; map<char,int> m_stoi; m_stoi[‘I‘]=1; m_stoi[‘V‘]=5; m_stoi[‘X‘]=10; m_stoi[‘L‘]=50; m_stoi[‘C‘]=100; m_stoi[‘D‘]=500; m_stoi[‘M‘]=1000; int i=nLength-1; int sum=m_stoi[s[i]];
i--; while(i>=0) { if(m_stoi[s[i+1]]>m_stoi[s[i]]) sum-=m_stoi[s[i]]; else sum+=m_stoi[s[i]]; i--; } return sum; } };
Roman to Integer,布布扣,bubuko.com
原文:http://www.cnblogs.com/awy-blog/p/3592744.html