【LeetCode】LeetCode——第13题:Roman to Integer

13. Roman to Integer

    My Submissions
Question Editorial Solution
Total Accepted: 82120  Total Submissions: 209456  Difficulty: Easy

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

Show Tags
Show Similar Problems













题目的大概意思是:输入一串罗马数字的字符串,输出对应的整数。

这道题难度等级:简单

与第12题的功能相反,思路差不多,整数也在1-3999之间。

为方便处理,我在字符串的最后加上了一个I,这样就不必考虑下标越界的问题了。

代码如下:

class Solution {
public:
    int romanToInt(string s) {
        int table[255];
		table['I'] = 1;		table['V'] = 5;		table['X'] = 10;	table['L'] = 50;
		table['C'] = 100;	table['D'] = 500;	table['M'] = 1000;
		int res = 0;
		s += "I";
		for (int i = 0; i < s.length() - 1; ++i){
            table[s[i]] >= table[s[i + 1]] ? (res += table[s[i]]): (res += table[s[i + 1]] - table[s[i]], ++i);
		}
		return res;
    }
};

也是做了一个表,利用查表法。

提交代码,顺利AC,Runtime: 36 ms

你可能感兴趣的:(TO,LeetCode,Integer,roman)