leetcode之旅(10)-Roman to Integer

题目描述:

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;   
    }
}

转载于:https://my.oschina.net/fengsehng/blog/784505

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值