419.Roman to Integer-罗马数字转整数(中等题)

罗马数字转整数

  1. 题目

    给定一个罗马数字,将其转换成整数。
    返回的结果要求在1到3999的范围内。

  2. 说明

    什么是 罗马数字?
    https://en.wikipedia.org/wiki/Roman_numerals
    https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
    http://baike.baidu.com/view/42061.htm

  3. 样例

    IV -> 4
    XII -> 12
    XXI -> 21
    XCIX -> 99

  4. 题解

    从后向前遍历字符串,如果后面的大于前面的则减去,反之则相加。

public class Solution {
    /**
     * @param s Roman representation
     * @return an integer
     */
    public int romanToInt(String s) {
        Map<Character, Integer> m = new HashMap<Character, Integer>();
        m.put('I', 1);
        m.put('V', 5);
        m.put('X', 10);
        m.put('L', 50);
        m.put('C', 100);
        m.put('D', 500);
        m.put('M', 1000);
        int res = m.get(s.charAt(s.length()-1));
        for (int i=s.length()-2;i>=0;i--)
        {
            res += (m.get(s.charAt(i+1)) <= m.get(s.charAt(i))) ? m.get(s.charAt(i)) : -m.get(s.charAt(i));
        }
        return res;
    }
}

Last Update 2016.11.17

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值