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

LeetCode——Roman to Integer

时间:2014-06-30 09:52:40      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:leetcode

Given a roman numeral, convert it to an integer.

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

给定一个罗马数字,把它转换成一个整数。

把罗马数字字符串转换成字符数组先,如下表,每个数字仅对应一个字符,而且字符不一样。故可从头开始取值进行对应。

The Roman Symbols

The Romans used a special method of showing numbers, based on the following symbols:

1
5
10
50
100
500
1000
I
V
X
L
C
D
M

	public int romanToInt(String s) {
		Map<Character, Integer> romans = new HashMap<Character, Integer>();
		romans.put('I', 1);
		romans.put('V', 5);
		romans.put('X', 10);
		romans.put('L', 50);
		romans.put('C', 100);
		romans.put('D', 500);
		romans.put('M', 1000);
		char[] ch = s.toCharArray();
		int num = 0, val = 0;
		for (int i = 0; i < ch.length; i++) {
			val = romans.get(ch[i]);
			if (i == ch.length - 1 || romans.get(ch[i + 1]) <= val)
				num += val;
			else
				num -= val;
		}
		return num;
	}

Reference:http://www.mathsisfun.com/roman-numerals.html

LeetCode——Roman to Integer,布布扣,bubuko.com

LeetCode——Roman to Integer

标签:leetcode

原文地址:http://blog.csdn.net/laozhaokun/article/details/35584911

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