首页 > 试题广场 >

罗马数字转整数

[编程题]罗马数字转整数
  • 热度指数:3000 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。

字符          数值
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。

通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:

I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 

C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。

给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。

示例1

输入

"III"

输出

3
示例2

输入

"LVIII"

输出

58

说明

L = 50, V= 5, III = 3.

def rome_translate_int(rome_str):
    rome_dict = {
    "I":1,
    "V":5,
    "X":10,
    "L":50,
    "C":100,
    "D":500,
    "M":1000
    }
    sum = 0

    for index in range(0,len(rome_str)):
        # print (index,rome_str[index],rome_dict[rome_str[index]])
        if (index == (len(rome_str)-1)):
            sum += rome_dict[rome_str[index]]
        elif rome_dict[rome_str[index]] < rome_dict[rome_str[index+1]]:
            sum += - rome_dict[rome_str[index]]
        else :
            sum +=  rome_dict[rome_str[index]]
    print (sum)

rome_translate_int("VII")


发表于 2021-03-16 09:12:58 回复(1)
/**
 * -------简单粗暴的解法
 * @param s string字符串 
 * @return int整型
 */

function romanToInt(s) {
    let StrObj = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }
    let specialArr = [];
    let intNum = 0;
    let strArr = s.split('');
    for (let i = 0; i < strArr.length - 1; i++) {
        // 只判断到倒数第二个元素的位置
        if (StrObj[strArr[i]] >= StrObj[strArr[i + 1]]) {
            intNum += StrObj[strArr[i]];
        } else {
            specialArr.push(i)
            i++;
        }
    }
    if (specialArr[specialArr.length - 1] != strArr.length - 2)
        intNum += StrObj[strArr[strArr.length - 1]];
    if (specialArr.length === 0) {
        return intNum;
    } else {
        for (let j = 0; j < specialArr.length; j++) {
            intNum += StrObj[strArr[specialArr[j] + 1]] - StrObj[strArr[specialArr[j]]];
        }
        return intNum;
    }
}

发表于 2021-03-09 13:00:16 回复(0)
functionromanToInt( s ) {
    // write code here
    let arr = ['M','D','C','L','X','V','I'];
    let val = [1000,500,100,50,10,5,1];
    let sum = 0;
    s.replace(/(C?[DM])|(X?[LC])|(I?[XV])|I/g,(value)=>{
        //console.log(value);
        if(value.length === 2){
           sum+= val[arr.indexOf(value[1])] - val[arr.indexOf(value[0])];
        }else{
            sum+= val[arr.indexOf(value)];
        }
    })
    return sum;
}

发表于 2021-03-18 02:30:36 回复(0)
Hop头像 Hop
public int romanToInt (String s) {
        char[] chars = s.toCharArray();
        int sum = 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);

        for (int i = 0; i < chars.length; i++) {
            if(i<chars.length-1 && map.get(chars[i]+"") < map.get(chars[i+1]+"")){
                sum -=  map.get(chars[i]+"");
            }else {
                sum +=  map.get(chars[i]+"");
            }
        }

        return sum;
    }


发表于 2021-03-04 17:32:46 回复(0)
import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int romanToInt (String s) {
        HashMap<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);
        if(s == null || "".equals(s)){
            return 0;
        }
        if(s.length() == 1) return map.get(s.charAt(0));
        int res = 0;
        for(int i=0;i<s.length();i++){
            if(i<s.length() - 1&&map.get(s.charAt(i)) < map.get(s.charAt(i+1))){
                if(s.charAt(i)=='I' && (s.charAt(i+1) == 'V'|| s.charAt(i+1)=='X')){
                    res -= map.get(s.charAt(i));
                }else if(s.charAt(i)=='X' && (s.charAt(i+1) == 'L'|| s.charAt(i+1)=='C')){
                    res -= map.get(s.charAt(i));
                }else if(s.charAt(i)=='C' && (s.charAt(i+1) == 'D'|| s.charAt(i+1)=='M')){
                    res -= map.get(s.charAt(i));
                }
            }else{
                res += map.get(s.charAt(i));
            }
        }
        return res;
    }
}
发表于 2021-03-12 21:11:40 回复(0)
leetcode第13题,从低位向高位进行遍历,对数字进行累加即可
import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int romanToInt (String s) {
        // write code here
        if(s == null || s.length() == 0)
            return 0;
        HashMap<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);
        int res = 0;
        for(int i = s.length() - 1; i >= 0; i--){
            if(i >= 1 && s.charAt(i) == 'V' && s.charAt(i - 1) == 'I'){
                res += 4;
                i --;
            }else if(i >= 1 && s.charAt(i) == 'X' && s.charAt(i - 1) == 'I'){
                res += 9;
                i --;
            }else if(i >= 1 && s.charAt(i) == 'L' && s.charAt(i - 1) == 'X'){
                res += 40;
                i --;
            }else if(i >= 1 && s.charAt(i) == 'C' && s.charAt(i - 1) == 'X'){
                res += 90;
                i --;
            }else if(i >= 1 && s.charAt(i) == 'D' && s.charAt(i - 1) == 'C'){
                res += 400;
                i --;
            }else if(i >= 1 && s.charAt(i) == 'M' && s.charAt(i - 1) == 'C'){
                res += 900;
                i --;
            }else
                res += map.get(s.charAt(i));
        }
        return res;
    }
}

发表于 2021-07-23 17:41:10 回复(0)
function romanToInt(s) {
    // write code here
    let num= 0;
    let map = new Map();
    map.set("IV", 4);
    map.set("IX", 9);
    map.set("XL", 40);
    map.set("XC", 90);
    map.set("CD", 400);
    map.set("CM", 900);
    map.set("I", 1);
    map.set("V", 5);
    map.set("X", 10);
    map.set("L", 50);
    map.set("C", 100);
    map.set("D", 500);
    map.set("M", 1000);
    for (let i= 0; i < s.length; ) {
        if (map.has(s[i] + s[i + 1])) {
            num+= map.get(s[i] + s[i + 1]);
            i = i + 2;
        } else {
           num+= map.get(s[i]);
            i = i + 1;
        }
    }
    return num;
}
发表于 2023-06-22 08:39:01 回复(0)
简单模拟
import java.util.*;


public class Solution {
    public int romanToInt (String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>(){{
            put('I', 1);
            put('V', 5);
            put('X', 10);
            put('L', 50);
            put('C', 100);
            put('D', 500);
            put('M', 1000);
        }};
        char[] cs = s.toCharArray();
        int n = cs.length;

        int res = map.get(cs[n - 1]);

        for (int i = n - 2; i >= 0; i--) {
            int cur = map.get(cs[i]);
            int last = map.get(cs[i + 1]);
            if (cur >= last) {
                res += cur;
            } else {
                res -= cur;
            }
        }

        return res;
    }
}

发表于 2022-03-28 10:00:41 回复(0)
import java.util.*;


public class Solution {
    /**
     *
     * @param s string字符串
     * @return int整型
     */
    public int romanToInt (String s) {
        // write code here
        char[] ch = s.toCharArray();
        int sum = 0;
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        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);

        int len = ch.length;
        boolean flag = true;
        if(len==0){
            return 0;
        }
        for(int i=0; i<len; i++){
           if(i<len-1){
                if(map.get(ch[i])<map.get(ch[i+1])){
                    sum += map.get(ch[i+1])-map.get(ch[i]);
                    i++;
                    flag = false;
                }else{
                    sum += map.get(ch[i]);
                }
           }else if((i==len-1)&&flag){
               sum += map.get(ch[len-1]);
           }
           
        }
        return sum;
    }
}
发表于 2022-03-19 16:28:58 回复(0)
public int romanToInt (String s) {
        int values[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};
        String reps[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        int i=0;
        int count=0;
        for(;i<reps.length;i++){
            if(s.indexOf(reps[i])==0)
                break;
        }
        for(;i<reps.length;i++){
            while(s.indexOf(reps[i])==0){
                 count+=values[i];
                s=s.substring(reps[i].length());
            }
                 
        }
        return count;
    }

发表于 2022-02-07 14:33:42 回复(0)
import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int romanToInt (String s) {
        HashMap<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);
        char[] ch=s.toCharArray();
        if(s.length()==1){
            return map.get(ch[0]);
        }
        int res=0;
        int flag=1;
        for(int i=ch.length-1;i>0;i--){
            if(map.get(ch[i])<=map.get(ch[i-1])){
                res+=map.get(ch[i])*flag;
                flag=1;
            }else {
                flag=-1;
                res+=map.get(ch[i]);
            }
        }
        res+=map.get(ch[0])*flag;
        return res;
    }
}

发表于 2021-09-07 16:14:57 回复(0)
class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    char hash[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
    int nums[7] = {1, 5, 10, 50, 100, 500, 1000};
    int romanToInt(string s) {
        int l = s.length();
        int k = 0, res = 0;
        while (l--) {
            for (int i = 0; i < 7; i++) {
                if (s[l] == hash[i]) {
                    if (i < k) {
                        res -= nums[i];
                    }
                    else {
                        res += nums[i];
                        k = i;
                    }
                    break;
                }
            }
        }
        return res;
    }
};

发表于 2021-07-27 21:05:51 回复(0)
这个题目自己最开始做的有问题是在特殊情况考虑的时候, 我自己认为只有字符串是那中情况中的一种,才符合。后面改成了只要子串中包含即可。这个题目采用了缓存,双指针完成。
import java.util.*;


public class Solution {
    static Map<String, Integer> exception = new HashMap<>();
    static Map<Character, Integer> hash = new HashMap<>();
    static {
        exception.put("IV", 4);
        exception.put("IX", 9);
        exception.put("XL", 40);
        exception.put("XC", 90);
        exception.put("CD", 400);
        exception.put("CM", 900);

        hash.put('I', 1);
        hash.put('V', 5);
        hash.put('X', 10);
        hash.put('L', 50);
        hash.put('C', 100);
        hash.put('D', 500);
        hash.put('M', 1000);
    }

    public int romanToInt (String s) {
        int result = exception.getOrDefault(s, 0);

        if (result == 0) {
            char[] chars = s.toCharArray();
            int cur = 0;
            int next = 0;
            int len = chars.length;
            int tmp = 0;

            while (cur < len) {
                if (chars[cur] == 'I' || chars[cur] == 'X' || chars[cur] == 'C') {
                    next = cur + 1;
                    if (next < len) {
                        StringBuilder str = new StringBuilder();
                        str.append(chars[cur]).append(chars[next]);
                        tmp = exception.getOrDefault(str.toString(), 0);
                    }

                    if (tmp == 0) {
                       tmp = hash.get(chars[cur]);
                       cur++;
                    } else {
                        cur = next + 1;
                    }
                } else {
                    tmp = hash.get(chars[cur]);
                    cur++;
                }

                result += tmp;
            }
        }

        return result;
    }
}



发表于 2021-07-17 20:41:30 回复(0)
import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int romanToInt (String s) {
        // write code here
        int ans = 0;
        int n = s.length();
        for (int i = 0; i < n; i++) {
            
            if(i < n - 1 && getValue(s.charAt(i)) < getValue(s.charAt(i + 1))) {
                ans -= getValue(s.charAt(i));
            }
            else {
                ans += getValue(s.charAt(i));
            }
        }
        
        return ans;
    }
    
    public int getValue(char ch) {
        switch(ch){
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
        
    }
}


发表于 2021-07-16 15:47:09 回复(0)
#
# 
# @param s string字符串 
# @return int整型
#
class Solution:
    def romanToInt(self , s ):
        # write code here
        dic = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        ans = 0
        N = len(s)
        for i in range(N - 1):
            if dic[s[i]] < dic[s[i + 1]]:
                ans -= dic[s[i]]
            else:
                ans += dic[s[i]]
        ans += dic[s[N - 1]]
        return ans

发表于 2021-07-09 21:11:33 回复(0)

#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
    string s = "MCMXCIV";
    int i = 0; int result = 0;
    unordered_map<string, int> m = { {"I", 1}, {"IV", 4}, {"IX", 9}, {"V", 5}, {"X", 10}, {"XL", 40}, {"XC", 90}, {"L", 50}, {"C", 100}, {"CD", 400}, {"CM", 900}, {"D", 500}, {"M", 1000} };
    while (i < s.length()) {
        string a = s.substr(i, 2);
       
        if (m[a] != NULL) {

            result = result + m[a];
            i = i + 2;
        }
        else {
            result = result + m[s.substr(i, 1)];
            i = i + 1;
        }

    }
    return result;
}


发表于 2021-07-02 16:08:27 回复(0)
package main

/**
 * 
 * @param s string字符串 
 * @return int整型
*/

var romanMap = map[byte]int {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000,
}
func romanToInt( s string ) int {
    // write code here
    if len(s) == 0 {
        return 0
    }
    res := 0
    for i := 0; i < len(s) - 1; i++ {
        if romanMap[s[i]] < romanMap[s[i+1]] {
            res -= romanMap[s[i]]
        } else {
            res += romanMap[s[i]]
        }
    }
    res += romanMap[s[len(s) - 1]]
    return res
}
发表于 2021-05-16 02:59:03 回复(0)
 public static int romanToInt(String s) {
        int num = 0;

        LinkedHashMap<String, String[]> map = new LinkedHashMap<>();
        map.put("M", new String[]{"1000", "D"});
        map.put("D", new String[]{"500", "C"});
        map.put("C", new String[]{"100", "L"});
        map.put("L", new String[]{"50", "X"});
        map.put("X", new String[]{"10", "V"});
        map.put("V", new String[]{"5", "I"});
        map.put("I", new String[]{"1"});

        // 全部相加
        char[] chars = s.toCharArray();
        for (char cha:chars) {
            num = num + Integer.parseInt(map.get(""+cha)[0]);
        }

        // 减掉左边的*2
        HashMap<String, Integer> numMap = new HashMap<>();
        for (char cha:chars) {
            String[] strings = map.get("" + cha);
            if(numMap.containsKey(cha)){
                numMap.put(""+cha,numMap.get(cha)+1);
            }else{
                if(!"I".equals(""+cha)){
                    num = num - (numMap.containsKey(strings[1]) ? numMap.get(strings[1])*Integer.parseInt(map.get(strings[1])[0])*2 : 0 );
                }
                numMap.put(""+cha,1);
            }
        }

        return num;
    }

发表于 2021-03-30 17:45:24 回复(0)
import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int romanToInt (String s) {
        // write code here
        Map<Character, Integer> map = new HashMap<>(7);
        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);

        char[] sc = s.toCharArray();
        int n = sc.length;
        int ans = 0, cur, next;
        for (int i = 0; i < n; ) {
            cur = map.get(sc[i]);
            next = i + 1 < n ? map.get(sc[i + 1]) : 0;

            if (cur < next) {
                ans += next - cur;
                i += 2;
            } else {
                ans += cur;
                ++i;
            }
        }
        return ans;
    }
}

发表于 2021-03-26 21:09:55 回复(0)
class Solution:
    def romanToInt(self, s: str) -> int:
        d = {'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000}
        return sum(d.get(s[max(i-1, 0):i+1], d[n]) for i, n in enumerate(s))

作者:QQqun902025048
链接:https://leetcode-cn.com/problems/roman-to-integer/solution/2-xing-python-on-by-knifezhu/
来源:力扣(LeetCode)



发表于 2021-03-11 10:54:18 回复(0)