[leetcode] 13. Roman to Integer

来源:互联网 发布:淘宝网店怎么激活 编辑:程序博客网 时间:2024/06/05 17:46

题目链接:https://leetcode.com/problems/roman-to-integer/

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

思路

罗马数字总共有七个 即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。其数字之间可以组合来表示任意的数字,但是不可以进行运算。

其组合规律如下:

左加右减:

  1. 较大的罗马数字右边记上较小的罗马数字,表示大数加小数

  2. 较大的罗马数字左边记上较小的罗马数字,表示大数减小数

  3. 左减的数字只限于I、X、C

  4. 左减时不可以跨位,如果99不可以写成IC,只能写成XCIX

  5. 左减只能有一位。如8写成VIII,而非IIX

  6. 右加最多三位。如14写成XIV,而非XIIII

OK,基本的规则就这些。

    class Solution {      public:          int romanToInt(string s) {              hash['I'] = 1;              hash['V'] = 5;              hash['X'] = 10;              hash['L'] = 50;              hash['C'] = 100;              hash['D'] = 500;              hash['M'] = 1000;              int cnt = 0;              for(int i =0; i< s.size(); i++)              {                  cnt += hash[s[i]];                  if(i>0 && hash[s[i]] > hash[s[i-1]])                      cnt -= 2* hash[s[i-1]];              }              return cnt;          }      private:          unordered_map<char, int> hash;      };