现在的位置: 首页 > 综合 > 正文

LeetCode OJ : Roman to Integer

2018年04月25日 ⁄ 综合 ⁄ 共 973字 ⁄ 字号 评论关闭

Roman to Integer

链接:https://leetcode.com/problems/roman-to-integer/

题解:

这题主要要了解罗马数字的规则

基本字符    相应的阿拉伯数字表示为
I                 1
V                5
X                10
L                 50
C                100
D                500
M               1000

1、基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。
2、不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。
3、V 和X 左边的小数字只能用Ⅰ。
4、L 和C 左边的小数字只能用X。
5、D 和M 左边的小数字只能用C。

百度百科:http://baike.baidu.com/link?url=rq2stCv2Cr_jdFkHdrMVmkTKdpVJkjQUnSudjoIW8mBThWqlTCzo1lsH6IWUGQ0REsDrNN3pfhW0c392gjoRma

代码:

public class Solution {
	    public int romanToInt(String s) {
	        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
	        s=s.toUpperCase();
	        hm.put('I',1);
	        hm.put('V',5);
	        hm.put('X',10);
	        hm.put('L',50);
	        hm.put('C',100);
	        hm.put('D',500);
	        hm.put('M',1000);
	        int sum=0,len=s.length();
	        for(int i=0,j;i<len;++i){
	            j=i+1;
	            if(j<len&&hm.get(s.charAt(i))<hm.get(s.charAt(j))){
	                sum+=hm.get(s.charAt(j))-hm.get(s.charAt(i));
	                i=j;
	            }
	            else{
	                sum+=hm.get(s.charAt(i));
	            }
	        }
	        return sum;
	    }
	}

来源:http://blog.csdn.net/acm_ted/article/details/44280409

抱歉!评论已关闭.