【LeetCode】0013——罗马数字转整数

题目描述

【LeetCode】0013——罗马数字转整数_第1张图片
【LeetCode】0013——罗马数字转整数_第2张图片

解题思路

本题只是上一个题目【整数转罗马数字】逆过程,需要注意的是,在遇到I、X、C时我们要继续判断它的下一个字符是什么

1、Java代码

class Solution {
    public int romanToInt(String s) {
        int result = 0; //存储结果
        char[] lm = s.toCharArray();
        int len = lm.length;
        for(int i = 0; i < len; i++){ //遍历每个罗马字符
            if(lm[i] == 'I'){
                if((i+1) < len && lm[i+1] == 'V'){
                    result += 4;
                    i++;
                }else if((i+1) < len && lm[i+1] == 'X'){
                    result += 9;
                    i++;
                }else{
                    result += 1;
                }
            }else if(lm[i] == 'V'){
                result += 5;
            }else if(lm[i] == 'X'){
                if((i+1) < len && lm[i+1] == 'L'){
                    result += 40;
                    i++;
                }else if((i+1) < len && lm[i+1] == 'C'){
                    result += 90;
                    i++;
                }else{
                    result += 10;
                }
            }else if(lm[i] == 'L'){
                result += 50;
            }else if(lm[i] == 'C'){
                if((i+1) < len && lm[i+1] == 'D'){
                    result += 400;
                    i++;
                }else if((i+1) < len && lm[i+1] == 'M'){
                    result += 900;
                    i++;
                }else{
                    result += 100;
                }
            }else if(lm[i] == 'D'){
                result += 500;
            }else if(lm[i] == 'M'){
                result += 1000;
            }
        }
        return result;
    }
}
class Solution {
    public int romanToInt(String s) {
    	int result = 0;  //存储结果
        Map<Character, Integer> mp = new HashMap<Character, Integer>();
        mp.put('I', 1);
        mp.put('V', 5);
        mp.put('X', 10);
        mp.put('L', 50);
        mp.put('C', 100);
        mp.put('D', 500);
        mp.put('M', 1000);
        
        
       //遍历罗马数字
        for(int i = 0; i < s.length(); i++){
            if(i < s.length() - 1 && mp.get(s.charAt(i)) < mp.get(s.charAt(i+1))){
                result -= mp.get(s.charAt(i));
            }else{
                result += mp.get(s.charAt(i));
            }
        }
        return result;
    }
}

2、Python3代码

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
        num = 0
        for i in range(len(s)):
            if i < len(s) - 1 and dic[s[i]] < dic[s[i + 1]]:
                num -= int(dic[s[i]])
            else:
                num += int(dic[s[i]])
        return num

你可能感兴趣的:(算法编程)