LeetCode 013. Roman to Integer

Roman to Integer

 

Given a roman numeral, convert it to an integer.

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






从左至右进行遍历,如果当前的字符大于或等于后一个字符,那么总和加上该罗马字符对应的数值,否则则减去当前字符对应的数值。

class Solution 
{
public:
    int romanToInt(string s) 
	{
		char str[7] = { 'M', 'D', 'C', 'L', 'X', 'V', 'I'};
		int val[7] = {1000, 500, 100, 50, 10, 5, 1};
		map<char, int>dict;
		for(int i=0; i<7; i++)
			dict.insert(pair<char, int>(str[i],val[i]));
        int len = s.length();
		int j = 0, sum = 0;
		while(j < len-1)
		{
			if(dict[s[j]] >= dict[s[j+1]])
				sum += dict[s[j++]];
			else
				sum -= dict[s[j++]];
		}
		sum += dict[s[len-1]];
		return sum;
    }
};


猜你喜欢

转载自blog.csdn.net/wanghuiqi2008/article/details/42809571