您的位置:首页 > 其它

leetcode之旅(10)-Roman to Integer

2016-03-29 22:57 471 查看

题目描述:

Given a roman numeral, convert it to an integer.

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

Subscribe to see which companies asked this question


预备知识:

记数方法

基本字符

I

V

X

L

C

D

M

相应的阿拉伯数字表示为

1

5

10

50

100

500

1000

1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;

2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;

3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;

4、正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)

5、在一个数的上面画一条横线,表示这个数扩大1000倍。 ##

思路:

一个罗马字符对应一个数字权,那么就可以用数据结构map

对于s中出现的每一个罗马字符从右到左(无低位高位这么一说),如果权值在变大,则权相加

如果变小了,则减去这个权值 ##

代码:

import java.util.HashMap;
import java.util.Map;

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

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