LeetCode每日一题:roman to integer

2017-07-05  本文已影响7人  yoshino

问题描述

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

问题分析

罗马数字转int,了解规则后还是很容易的

I 1
V 5
X 10
L 50
C 100
D 500
M 1000
相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
正常使用时、连写的数字重复不得超过三次;
在一个数的上面画一条横线、表示这个数扩大 1000 倍。

代码实现

public int romanToInt(String s) {
        HashMap<Character, Integer> hashMap = new HashMap<>();
        hashMap.put('I', 1);
        hashMap.put('V', 5);
        hashMap.put('X', 10);
        hashMap.put('L', 50);
        hashMap.put('C', 100);
        hashMap.put('D', 500);
        hashMap.put('M', 1000);
        int result = 0, preValue = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            int curValue = hashMap.get(s.charAt(i));
            if (curValue < preValue) result = result - curValue;
            else result = result + curValue;
            preValue = curValue;
        }
        return result;
    }
上一篇 下一篇

猜你喜欢

热点阅读