首页 > 其他 > 详细

【简单】罗马数字转整数

时间:2021-05-05 21:54:20      阅读:30      评论:0      收藏:0      [点我收藏+]

https://leetcode-cn.com/problems/roman-to-integer/

能比较快想到的一个方法:

public class RomanToInt {
    public static int romanToInt(String s) {
        int ret = 0;
        Map<String,Integer> map = new HashMap<>();
        Map<String,Integer> mapCombine = 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);
        mapCombine.put("IV",4);
        mapCombine.put("IX",9);
        mapCombine.put("XL",40);
        mapCombine.put("XC",90);
        mapCombine.put("CD",400);
        mapCombine.put("CM",900);
        char[] charArr = s.toCharArray();
        int i = 0;
        if(s.length() == 1){
            ret += map.get(String.valueOf(charArr[0]));
        }else{
            while(i < s.length()){
                if((i+1) >= s.length()) {
                    ret += map.get(String.valueOf(charArr[i]));
                    break;
                }
                if(mapCombine.containsKey(String.valueOf(charArr[i]) + String.valueOf(charArr[i+1]))){
                    ret += mapCombine.get(String.valueOf(charArr[i]) + String.valueOf(charArr[i+1]));
                    i=i+2;
                 }else{
                    ret += map.get(String.valueOf(charArr[i]));
                    i++;
                }
            }
        }
        return ret;
    }
    public static void main(String[] args){
        System.out.println(romanToInt("III"));
        System.out.println(romanToInt("IV"));
        System.out.println(romanToInt("IX"));
        System.out.println(romanToInt("LVIII"));
        System.out.println(romanToInt("MCMXCIV"));
    }
}

  网上看到还有一个更直观的解法

        int ret = 0;
        Map<String,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);
        map.put("O",4);
        map.put("P",9);
        map.put("Q",40);
        map.put("R",90);
        map.put("S",400);
        map.put("T",900);
        s = s.replaceAll("IV","O");
        s = s.replaceAll("IX","P");
        s = s.replaceAll("XL","Q");
        s = s.replaceAll("XC","R");
        s = s.replaceAll("CD","S");
        s = s.replaceAll("CM","T");
        char[] charArr = s.toCharArray();
        for(char c : charArr){
            ret += map.get(String.valueOf(c));
        }
        return ret;

  

 

【简单】罗马数字转整数

原文:https://www.cnblogs.com/cstar/p/14732675.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!