您的位置:首页 > 编程语言 > Java开发

[LeetCode][Java] Roman to Integer

2017-07-12 11:05 351 查看

题目:

Given a roman numeral, convert it to an integer.

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


题意:

给定一个罗马数字,将其转化为整数。

给定的输入保证在1-3999之间


算法分析:


 * 罗马数字规则:

 * 1, 罗马数字共同拥有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。

 * 罗马数字中没有“0”。

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

 * 3, 右加左减:

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

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


AC代码:

public class Solution
{
private  int sss;

public  int romanToInt(String s)
{
Map<Character, Integer> dct=new HashMap<Character, Integer>() ;
dct.put('I', 1);
dct.put('i', 1);
dct.put('V', 5);
dct.put('v', 5);
dct.put('X', 10);
dct.put('x', 10);
dct.put('L', 50);
dct.put('l', 50);
dct.put('C', 100);
dct.put('c', 100);
dct.put('D', 500);
dct.put('d', 500);
dct.put('M', 1000);
dct.put('m', 1000);
int sum = 0, j;
for(int i = 0; i < s.length(); ++i)
{
j = i+1;
if(j < s.length() && dct.get(s.charAt(j)) > dct.get(s.charAt(i)))
{
sum += dct.get(s.charAt(j)) - dct.get(s.charAt(i));
i = j;
}
else
sum += dct.get(s.charAt(i));
}
return sum;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: