13. Roman to Integer(easy)

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3
Example 2:

Input: "IV"
Output: 4
Example 3:

Input: "IX"
Output: 9
Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

分析:
把每一个字母代表的数字存在hashmap里,从第一个字符开始读字符串,如果这个字符比下一个字符代表的数字小,说明需要减去这个字符。如果这个字符比下一个字符代表的数字大,说明要加上这个字符。

Java语言:

public int romanToInt(String s) {
        int res = 0;
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
        for (int i = 0; i < s.length(); i++) {
            if (i != s.length() - 1 && map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
                res -= map.get(s.charAt(i));
                res += map.get(s.charAt(i + 1));
                i++;
            } else {
                res += map.get(s.charAt(i));
            }
        }
        return res;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,724评论 0 10
  • 最近加入了樊登读书会,听了很多樊登老师讲解的书籍,多数是关于孩子教育的,这两天听了一本《不吼不叫》感受颇多,故...
    Wendy058阅读 417评论 1 3
  • 第1章 玩具不懂轻重 凌晨。 开门声在静谧的夜里,显得很突兀。 宋悠然却跑过去打开门,笑着张开双臂拥抱半夜回家的男...
    冰冰_36f5阅读 5,950评论 1 10
  • 情人节…… 一个我一直没过过的节日,从来不知道收到花和巧克力的感觉是怎样的惊喜。也不知道浪漫的约会是怎样的感觉……...
    木易miss阅读 216评论 0 1
  • 杭州三月的天好觉一下到了夏天,穿上了很久没穿的运动鞋和短袖,趁着这么好的天气,约上一帮好友打打球! 这个地方跟我同...
    蘑菇云MG阅读 635评论 0 5

友情链接更多精彩内容