[LeetCode]Roman to Integer

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;
	}
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值