Leetcode35: Roman to Integer

来源:互联网 发布:应用程序与网络端口 编辑:程序博客网 时间:2024/06/18 09:20

Given a roman numeral, convert it to an integer.

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

罗马数字规则:

1, 罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。

罗马数字中没有“0”。

2, 重复次数:一个罗马数字最多重复3次。

3, 右加左减:

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

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

4, 左减的数字有限制,仅限于I、X、C,且放在大数的左边只能用一个。

(*) V 和 X 左边的小数字只能用Ⅰ。

(*) L 和 C 左边的小数字只能用X。

(*) D 和 M 左 边的小数字只能用C。

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


转载地址:http://www.tuicool.com/articles/fUVNJb

0 0
原创粉丝点击