【LeetCode从零单刷】Roman to Integer

来源:互联网 发布:翻 墙软件 编辑:程序博客网 时间:2024/06/05 11:06

题目:

Given a roman numeral, convert it to an integer.

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

解答:

说实话这题目就是欺负中国人不了解罗马数字。可以参考维基百科中相关介绍:传送门。其中有性质如下:

  • 羅馬數字共有7個,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。
  • 右加左減:在較大的羅馬數字的右邊記上較小的羅馬數字,表示大數字加小數字。在較大的羅馬數字的左邊記上較小的羅馬數字,表示大數字减小數字。
  • 之后的事情就是查表,并且不考虑进制问题,一位一位的计数

    比较与右侧字母的大小关系,如果大于等于右侧字母则总和加上这个字母;否则减去这个字母。

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

    0 0
    原创粉丝点击