码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Roman to Integer

时间:2015-02-03 11:09:32      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:roman numerals

Q:Given a roman numeral, convert it to an integer.

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

该题是要将罗马数字转换成integer。罗马数字的定义可见维基百科:Roman numerals .

罗马数字是基于下面7个符号:

技术分享

罗马数字的1-10如下:I ,II,III,IV,V,VI,VII,VIII,IX ,X

计算规则很简单,从字符串的末端开始,重点是记录“上一个数”比“这个数”大或者小,来确定是加还是减。从后往前扫描简单一点。标准的计算规则维基上也有,还是贴上原汁原味的,理解更深刻吧。

Numbers are formed by combining symbols and adding the values. So II is two ones, i.e. 2, and XIII is a ten and three ones, i.e. 13. There is no zero in this system, so 207, for example, is CCVII, using the symbols for two hundreds, a five and two ones. 1066 is MLXVI, one thousand, fifty and ten, a five and a one.

Symbols are placed from left to right in order of value, starting with the largest. However, in a few specific cases,[2] to avoid four characters being repeated in succession (such as IIII or XXXX) these can be reduced using subtractive notation as follows:[3][4]

the numeral I can be placed before V and X to make 4 units (IV) and 9 units (IX) respectively
X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern[5]
An example using the above rules would be 1904: this is composed of 1 (one thousand), 9 (nine hundreds), 0 (zero tens), and 4 (four units). To write the Roman numeral, each of the non-zero digits should be treated separately. Thus 1,000 = M, 900 = CM, and 4 = IV. Therefore, 1904 is MCMIV.

Below are some examples of the modern use of Roman numerals:

1954 as MCMLIV, as in the trailer for the movie The Last Time I Saw Paris)[6]
1990 as MCMXC, used as the title of musical project Enigma's debut album MCMXC a.D., named after the year of its release.)
2014 as MMXIV, the year of the games of the XXII (22nd) Olympic Winter Games (in Sochi)
好了,最后贴上代码:

class Solution {
public:
	int romanToInt(string s) {
		int roman[100];
		roman['I'] = 1;
		roman['V'] = 5;
		roman['X'] = 10;
		roman['L'] = 50;
		roman['C'] = 100;
		roman['D'] = 500;
		roman['M'] = 1000;
		int len = s.length();
		int last = roman[s[len - 1]];
		int result = last;
		for (int i = len-2; i >= 0; i--){
			if (roman[s[i]] < last)
				result -= roman[s[i]];
			else
				result += roman[s[i]];
			last = roman[s[i]];
		}
		return result;
	}
};



[LeetCode]Roman to Integer

标签:roman numerals

原文地址:http://blog.csdn.net/kaitankedemao/article/details/43446147

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!