栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

罗马字转数字 算法面试

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

罗马字转数字 算法面试

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, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 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.

```

import java.util.HashMap;
class Solution {
    static HashMap map = new HashMap();
    
    static{
                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);
    }
    public int romanToInt(String s) {
        
        String lastSymbol = s.substring(s.length()-1);
        int lastValue = map.get(lastSymbol);
        int total = lastValue;;
        
        for(int i = s.length()-2; i>=0; i--)
        {
            String currentSymbol = s.substring(i, i+1);
            int currentValue = map.get(currentSymbol);
            if(currentValue < lastValue)
            {
                total = total - currentValue;
            }else{
                total += currentValue;
            }
            lastValue = currentValue;
        }
        
        
        return total;
    }
}

```

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/686559.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号