Roman to Integer

Given a roman numeral, convert it to an integer.

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


public int translate(String romanNum){
	int sum = 0;
	int[] in = new int[romanNum.length()];
	for(int i = 0; i != in.length; i++){
		in[i] = conv(romanNum.charAt(i));
		if(i != 0){
			if(in[i - 1] < in[i]){
				in[i -1] = - in[i - 1];
			}
		}
	}
	for(int t : in){
		sum += t;
	}
	return sum;
}

private int conv(char c){
	switch (c) {
		case 'I':return 1;
		case 'V':return 5;
		case 'X':return 10;
		case 'L':return 50;
		case 'C':return 100;
		case 'D':return 500;
		case 'M':return 1000;
		default:return -1;
	}
}

@Test
public void test(){
	Assert.assertEquals(1, translate("I"));
	Assert.assertEquals(5, translate("V"));
	Assert.assertEquals(10, translate("X"));
	Assert.assertEquals(50, translate("L"));
	Assert.assertEquals(100, translate("C"));
	Assert.assertEquals(500, translate("D"));
	Assert.assertEquals(1000, translate("M"));
	Assert.assertEquals(81, translate("LXXXI"));
	Assert.assertEquals(183, translate("CLXXXIII"));
	Assert.assertEquals(810, translate("DCCCX"));
	Assert.assertEquals(811, translate("DCCCXI"));
	Assert.assertEquals(1544, translate("MDXLIV"));
}
参考文献:


1.罗马数字(1~5000)-http://wenku.baidu.com/view/e91595bbf121dd36a32d8230.html?re=view

2.罗马数字-百度百科-http://baike.baidu.com/link?url=lsAsm1nWTalc4-cd32tDyMdySm9LA_yB4pmfis4zkB_tLjK34_EqMyxlx-ahzPPjBcl0lnD0Jhxfi7TyRmbhx_



你可能感兴趣的:(Roman to Integer)