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

Roman to Integer

时间:2015-08-06 22:37:33      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:leetcode

Given a roman numeral, convert it to an integer.

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


题目解析:题目看似比较简单但是背后隐藏了很多关于罗马数字表示的规则,查阅了一些资料主要规则如下

罗马数字规则:

1, 罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。罗马数字中没有“0”。

2, 重复次数:一个罗马数字最多重复3次。

3, 右加左减:


在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。

在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。

4, 左减的数字有限制,仅限于I、X、C,且放在大数的左边只能用一个。

(*) V 和 X 左边的小数字只能用Ⅰ。

(*) L 和 C 左边的小数字只能用X。

(*) D 和 M 左 边的小数字只能用C。

这样问题就好解决了

算法分析:主要是通过Hash表映射,其它很简单,上AC代码

public int romanToInt(String s) {
		// 安全性判断
		if (s == null || s.length() == 0)
			return 0;
		// hash表
		HashMap<Character, Integer> numMap = new HashMap<Character, Integer>();
		numMap.put('I', 1);
		numMap.put('V', 5);
		numMap.put('X', 10);
		numMap.put('L', 50);
		numMap.put('C', 100);
		numMap.put('D', 500);
		numMap.put('M', 1000);
		int len = s.length();
		int result = numMap.get(s.charAt(len - 1));
		for (int i = len - 2; i >= 0; i--) {
			// 比较罗马字符
			if (numMap.get(s.charAt(i + 1)) <=numMap.get(s.charAt(i))) {
				result = result + numMap.get(s.charAt(i));
			} else {
				result = result - numMap.get(s.charAt(i));
			}
		}
		return result;
	}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Roman to Integer

标签:leetcode

原文地址:http://blog.csdn.net/xsf50717/article/details/47321693

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