leetcode13 罗马数字转整数

news2025/6/9 17:10:55

题目描述:罗马数字由七种字符组成,分别为 I、V、X、L、C、D 和 M,对应的数值分别为 1、5、10、50、100、500 和 1000。在一般情况下,小的数字位于大的数字右边,但有特殊情况,如 IV 表示 4,IX 表示 9,XL 表示 40,XC 表示 90,CD 表示 400,CM 表示 900。给定一个罗马数字,需要将其转换成整数。

例如:罗马数字 2 写做 II ,即为两个并列的 1 。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。

 方法1 模拟

该方法的思想类似于“对号入座”,找到什么罗马符号对应的什么值就写进去,但是最关键的是要搞清楚前后的加减关系,以Roman=“MCMXCIV”为例,第二个位置上的C所对应的值要比第三个位置上的M所对应的值要小,关于前后是进行加法运算还是减法运算,可以看下图的图解,通过图解就可以清楚的知道该如何进行运算。 

 python完整代码:

class Solution:
    symbol_values = {
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000
    }
    def romanToInt(self, str):
        digital = 0  # 定义当前数字
        n = len(str)  # 罗马字数字长度
        for i, ch in enumerate(str):
            value = Solution.symbol_values[ch]
            if i < n - 1 and value < Solution.symbol_values[str[i + 1]]:
                digital -= value  # 左边比右边小--->减
            else:
                digital += value  # 左边比右边大--->加
        return digital

# 设置罗马数字
Roman = "MCMXCIV"
solution = Solution()
result = solution.romanToInt(Roman)
print("罗马数字转整数的结果为: ", result)

c++完整代码: 

#include<iostream>
#include<unordered_map>
using namespace  std;

class Solution{
private:
    unordered_map<char, int> symbol_values ={
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000}
    };
public:
    int romanToInt(string str){
        int digital = 0;
        int n = str.length();
        for(int i = 0;i < n;++i){
            int value = symbol_values[str[i]];
            if(i < n - 1 && value < symbol_values[str[i + 1]]){
                digital -= value;
            } else{
                digital += value;
            }
        }
        return digital;
    }
};

int main(){
    string Roman = {"MCMXCIV"};
    Solution solution;
    int result = solution.romanToInt(Roman);
    cout << Roman << " into roman digital " << result << endl;// 输出转换结果
    return 0;
}

java完整代码: 

import java.util.HashMap;

public class RomanToInt {
    HashMap<Character, Integer> symbolValues = 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);
    }};

    public int romanToInt(String str) {
        int digital = 0;
        int n = str.length();
        for (int i = 0; i < n; ++i) {
            int value = this.symbolValues.get(str.charAt(i));
            if (i < n - 1 && value < this.symbolValues.get(str.charAt(i + 1))) {
                digital -= value;
            } else {
                digital += value;
            }
        }
        return digital;
    }
    public static void main(String[] args) {
        // 创建 RomanToInt 类的实例
        RomanToInt converter = new RomanToInt();
        // 设置当前罗马数字
        String Roman = "MCMXCIV";
        // 调用方法将罗马数字转换为整数
        int result = converter.romanToInt(Roman);
        // 输出转换结果
        System.out.println("罗马数字转整数为: " + result);
    }
}

 方法2 贪心哈希表

该方法其实和上面的方法差不多,也是逐一逐二的遍历哈希表中存储的罗马字符,在根据所对应的值生成我们想要的整数,其中关键的还是怎样分清楚什么时候加,什么时候进行减。

 python完整代码:

class Solution:
    def romanToInt(self, str):  # 添加 self 参数
        roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}  # 哈希表
        digital = 0  # 整数结果

        for i in range(len(str)):  # 遍历每个字符
            # 如果当前字符比下一个字符小,则减去当前字符的值
            if i < len(str) - 1 and roman_dict[str[i]] < roman_dict[str[i + 1]]:
                digital -= roman_dict[str[i]]  # 当前字符比下一个字符小--->减
            else:
                digital += roman_dict[str[i]]  # 当前字符比下一个字符大--->加

        return digital

# 示例
Roman = "MCMXCIV"
solution = Solution()
integer_value = solution.romanToInt(Roman)
print(f"罗马数字 {Roman} 转换为整数为: {integer_value}")

c++完整代码:

#include <iostream>
#include <unordered_map>
using namespace std;

class Solution {
public:
    int romanToInt(string str) {
        unordered_map<char, int> roman_dict = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
        int digital = 0;

        for (int i = 0; i < str.length(); ++i) {
            // 如果当前字符比下一个字符小,则减去当前字符的值
            if (i < str.length() - 1 && roman_dict[str[i]] < roman_dict[str[i + 1]]) {
                digital -= roman_dict[str[i]];  //当前字符比下一个字符小--->减
            } else {
                digital += roman_dict[str[i]]; //当前字符比下一个字符大--->加
            }
        }
        return digital;
    }
};

int main() {
    Solution solution;
    string Roman = "MCMXCIV";
    int integer_value = solution.romanToInt(Roman);
    cout << "Roman digital " << Roman << " into int: " << integer_value << endl;
    return 0;
}

 java完整代码:

import java.util.HashMap;
public class RomanToInt1 {
    public int romanToInt(String str) {
        HashMap<Character, Integer> romanDict = new HashMap<>();
        romanDict.put('I', 1);
        romanDict.put('V', 5);
        romanDict.put('X', 10);
        romanDict.put('L', 50);
        romanDict.put('C', 100);
        romanDict.put('D', 500);
        romanDict.put('M', 1000);

        int digital = 0;

        for (int i = 0; i < str.length(); ++i) {
            // 如果当前字符比下一个字符小,则减去当前字符的值
            // 在Java中,charAt 是一个用于获取字符串中指定位置字符的方法。它是String类的一个成员方法
            // 语法为char charAt(int index) 
            // 其中,index 是字符串中字符的索引,从0开始计数。返回值是指定索引位置的字符
            if (i < str.length() - 1 && romanDict.get(str.charAt(i)) < romanDict.get(str.charAt(i + 1))) {
                digital -= romanDict.get(str.charAt(i));
            } else {
                digital += romanDict.get(str.charAt(i));
            }
        }

        return digital;
    }

    public static void main(String[] args) {
        RomanToInt1 solution = new RomanToInt1();
        String roman = "MCMXCIV";
        int integerValue = solution.romanToInt(roman);
        System.out.println("罗马数字 " + roman + " 转换为整数为: " + integerValue);
    }
}

 方法3 if-else方法

if-else方法的思路很简答,主要思想就是从罗马数字的最右边往左遍历,假如输入的都是图(a)中的罗马数字,那么我们根本不用费什么劲,直接划拉一遍,直接M对应1000,I对应1等等等等,然后把得到的对应的整数加一块就皆大欢喜了,但是最重要的问题是输入的罗马数字会出现图(b)所示的情况,那么怎么解决这种情况呢?方法很简单,我们图(a)中所对应的罗马数字的情况中再加上图(b)这种情况,也就是在当前位置再往前一位进行比较,如果出现图(b)的情况时,再补充上,最后全部遍历完后,把所有数字加一块就功成身退了。

  c++完整代码: 

// -*- coding: utf-8 -*-
// @Time    : 2024/1/4 10:28
// @Author  : 长沙有肥鱼
// @FileName: 罗马数字转整数_if.cpp
// @Software: CLion
// @Blog    : https://blog.csdn.net/weixin_53660567?spm=1010.2135.3001.5343

#include <iostream>
using namespace std;

class Solution {
public:
    int romanToInt(std::string str) {
        int len = str.length();
        int digital = 0;
        for (int i = len - 1; i >= 0; i--) {  //从右往左边遍历
            if (str[i] == 'V') {
                if (i - 1 >= 0 && str[i - 1] == 'I') {
                    //当V左边的罗马数字为I时 digital--->+4
                    //当V左边的罗马数字不为I时 digital--->+5 因为除I以外的罗马数字都比它大
                    digital += 4;
                    i--;
                    continue;
                } else {
                    digital += 5;
                    continue;
                }
            }
            if (str[i] == 'X') {
                //当X左边的罗马数字为X时 digital--->+9
                //当X左边的罗马数字不为I时 digital--->+10
                if (i - 1 >= 0 && str[i - 1] == 'I') {
                    digital += 9;
                    i--;
                    continue;
                } else {
                    digital += 10;
                    continue;
                }
            }
            if (str[i] == 'L') {
                if (i - 1 >= 0 && str[i - 1] == 'X') {
                    //当L左边的罗马数字为X时 digital--->+40
                    //当L左边的罗马数字不为X时 digital--->+50
                    digital += 40;
                    i--;
                    continue;
                } else {
                    digital += 50;
                    continue;
                }
            }
            if (str[i] == 'C') {
                if (i - 1 >= 0 && str[i - 1] == 'X') {
                    //当C左边的罗马数字为X时 digital--->+90
                    //当C左边的罗马数字不为X时 digital--->+100
                    digital += 90;
                    i--;
                    continue;
                } else {
                    digital += 100;
                    continue;
                }
            }
            if (str[i] == 'D') {
                if (i - 1 >= 0 && str[i - 1] == 'C') {
                    //当D左边的罗马数字为C时 digital--->+400
                    //当D左边的罗马数字不为C时 digital--->+500
                    digital += 400;
                    i--;
                    continue;
                } else {
                    digital += 500;
                    continue;
                }
            }
            if (str[i] == 'M') {
                if (i - 1 >= 0 && str[i - 1] == 'C') {
                    //当M左边的罗马数字为C时 digital--->+900
                    //当M左边的罗马数字不为C时 digital--->+1000
                    digital += 900;
                    i--;
                    continue;
                } else {
                    digital += 1000;
                    continue;
                }
            }
            if (str[i] == 'I') {
                //当L左边的罗马数字为I时 digital--->+1
                digital++;
            }
        }
        return digital;
    }
};

int main() {
    Solution solution;
    std::string roman = "MCMXCIV";
    int integerValue = solution.romanToInt(roman);
    std::cout << "Roman digital " << roman << " into int:  " << integerValue << std::endl;

    return 0;
}

python完整代码: 

# -*- coding: utf-8 -*-
# @Time    : 2024/1/4 10:22
# @Author  : 长沙有肥鱼
# @FileName: 罗马数字转整数_if_else.py
# @Software: PyCharm
# @Blog    : https://blog.csdn.net/weixin_53660567?spm=1010.2135.3001.5343
class Solution:
    def romanToInt(self, str):
        length = len(str)
        digital = 0

        i = length - 1
        while i >= 0:
            if str[i] == 'V':
                if i - 1 >= 0 and str[i - 1] == 'I':
                    digital += 4
                    i -= 1
                else:
                    digital += 5
                i -= 1
            elif str[i] == 'X':
                if i - 1 >= 0 and str[i - 1] == 'I':
                    digital += 9
                    i -= 1
                else:
                    digital += 10
                i -= 1
            elif str[i] == 'L':
                if i - 1 >= 0 and str[i - 1] == 'X':
                    digital += 40
                    i -= 1
                else:
                    digital += 50
                i -= 1
            elif str[i] == 'C':
                if i - 1 >= 0 and str[i - 1] == 'X':
                    digital += 90
                    i -= 1
                else:
                    digital += 100
                i -= 1
            elif str[i] == 'D':
                if i - 1 >= 0 and str[i - 1] == 'C':
                    digital += 400
                    i -= 1
                else:
                    digital += 500
                i -= 1
            elif str[i] == 'M':
                if i - 1 >= 0 and str[i - 1] == 'C':
                    digital += 900
                    i -= 1
                else:
                    digital += 1000
                i -= 1
            elif str[i] == 'I':
                digital += 1
        return digital

# 示例
solution = Solution()
roman_numeral = "MCMXCIV"
integer_value = solution.romanToInt(roman_numeral)
print(f"罗马数字 {roman_numeral} 转换为整数为: {integer_value}")

Java完整代码: 

public class RomanToInt2 {
    public int romanToInt(String str) {
        int len = str.length();
        int digital = 0;
        // 如果当前字符比下一个字符小,则减去当前字符的值
        // 在Java中,charAt 是一个用于获取字符串中指定位置字符的方法。它是String类的一个成员方法
        // 语法为char charAt(int index)
        // 其中,index 是字符串中字符的索引,从0开始计数。返回值是指定索引位置的字符
        for(int i = len - 1; i >= 0; i--) {
            if(str.charAt(i) == 'V') {
                if((i - 1 >= 0) && (str.charAt(i - 1) == 'I'))
                {
                    digital += 4;
                    i--;
                    continue;
                }
                else {
                    digital+=5;
                    continue;
                }
            }
            if(str.charAt(i) == 'X') {
                if((i - 1 >= 0) && (str.charAt(i - 1) == 'I'))
                {
                    digital += 9;
                    i--;
                    continue;
                }
                else {
                    digital += 10;
                    continue;
                }
            }
            if(str.charAt(i) == 'L') {
                if((i - 1 >= 0) && (str.charAt(i - 1) == 'X'))
                {
                    digital += 40;
                    i--;
                    continue;
                }
                else {
                    digital += 50;
                    continue;
                }
            }
            if(str.charAt(i) == 'C') {
                if((i - 1 >= 0) && (str.charAt(i - 1) == 'X'))
                {
                    digital += 90;
                    i--;
                    continue;
                }
                else {
                    digital += 100;
                    continue;
                }
            }
            if(str.charAt(i) == 'D') {
                if((i - 1 >= 0) && (str.charAt(i - 1) == 'C'))
                {
                    digital += 400;
                    i--;
                    continue;
                }
                else {
                    digital += 500;
                    continue;
                }
            }
            if(str.charAt(i) == 'M') {
                if((i - 1 >= 0) && (str.charAt(i - 1) == 'C'))
                {
                    digital += 900;
                    i--;
                    continue;
                }
                else {
                    digital += 1000;
                    continue;
                }
            }
            if(str.charAt(i) == 'I') {
                digital++;
            }
        }
        return digital;
    }
    public static void main(String[] args) {
        RomanToInt2 solution = new RomanToInt2();
        String roman = "MCMXCIV";
        int integerValue = solution.romanToInt(roman);
        System.out.println("罗马数字 " + roman + " 转换为整数为: " + integerValue);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1355094.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Spring Cloud之OpenFeign异常处理

简易原理图 原理基于请求头传递错误消息&#xff0c;利用aop和全局异常拦截机制实现。 服务提供者 远程调用本地方法b&#xff0c;throw异常出来FeignExceptionAspect AOP拦截处理异常到请求头中&#xff0c;继续throwGlobalExceptionHandler处理&#xff0c;返回响应Respons…

腾讯云Centos9使用docker的方式安装APISIX

在虚拟机中安装Docker、Docker-compose 安装Docker 清除旧版本的docker yum remove docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine 安装docker的依赖 yum install -y yum-utils device-ma…

NE555学习笔记-2024

实物图片 NE555引脚图 内部时序图 示列1&#xff0c;红外接收电路 红外接收电路的工作原理&#xff1a;在上述电路中&#xff0c;TSOP1738构成了该电路的主要组成部分&#xff0c;旨在检测来自任何来源的红外信号。这用于检测38 KHz范围的信号&#xff0c;因此命名为“TSOP173…

LeetCode 2487. 从链表中移除节点:单调栈

【LetMeFly】2487.从链表中移除节点&#xff1a;单调栈 力扣题目链接&#xff1a;https://leetcode.cn/problems/remove-nodes-from-linked-list/ 给你一个链表的头节点 head 。 移除每个右侧有一个更大数值的节点。 返回修改后链表的头节点 head 。 示例 1&#xff1a; 输…

详谈电商网站建设的四大流程!

在21世纪的互联网时代&#xff0c;电商网站的建设是每个企业发展不可缺少的一次机遇。企业商城网站建设成功也许会获得更大的了利润&#xff1b;如果网站建设不成功&#xff0c;那么也会带来一定的损失。所以建设电商网站不是那么一件简单的事情。那么电商网站制作流程是怎样的…

2024年【上海市安全员C3证】试题及解析及上海市安全员C3证模拟考试题

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 上海市安全员C3证试题及解析根据新上海市安全员C3证考试大纲要求&#xff0c;安全生产模拟考试一点通将上海市安全员C3证模拟考试试题进行汇编&#xff0c;组成一套上海市安全员C3证全真模拟考试试题&#xff0c;学员…

el-select下拉框 change事件返回该项所有数据

主要代码 value-key <template><div><el-selectv-model"value"value-key"label"placeholder"请选择"change"selectChange"><el-optionv-for"item in options":key"item.label":label"…

数据库:基础SQL知识+SQL实验2

&#xff08;1&#xff09;基础知识&#xff1a; 1.JOIN&#xff08;连接&#xff09;&#xff1a; 连接操作用于根据指定的条件将两个或多个表中的数据行合并在一起。JOIN 可以根据不同的条件和方式执行&#xff0c;包括等值连接、不等值连接等。 &#xff08;1&#xff09…

5分钟了解接口测试

接口测试是指对系统接口进行测试的一种质量保障手段&#xff0c;主要是验证接口的功能、性能、安全性等方面是否符合预期。 在接口测试中&#xff0c;可以测试以下内容&#xff1a; 功能测试&#xff1a;验证接口的输入和输出是否符合预期&#xff0c;包括参数的正确性、返回结…

【Docker】docker部署conda并激活环境

原文作者&#xff1a;我辈李想 版权声明&#xff1a;文章原创&#xff0c;转载时请务必加上原文超链接、作者信息和本声明。 文章目录 前言一、新建dockerfile文件二、使用build创建镜像1.报错&#xff1a;Your shell has not been properly configured to use conda activate.…

基于LLM+RAG的问答

每日推荐一篇专注于解决实际问题的外文&#xff0c;精准翻译并深入解读其要点&#xff0c;助力读者培养实际问题解决和代码动手的能力。 欢迎关注公众号 原文标题&#xff1a;LLMRAG based Question Answering 原文地址&#xff1a;https://teemukanstren.com/2023/12/25/llm…

【网络安全】上网行为代理服务器Network Agent配置

文章目录 About Network Agent SettingsIgnore Internal TrafficInternal Traffic to MonitorAdditional SettingsBandwidth calculation intervalLog protocol traffic periodically 推荐阅读 本文基于websense &#xff08;现在称为Forcepoint&#xff09;的Network Agent 配…

npm发布js工具包

一、创建项目 1、在github上创建一个项目&#xff0c;然后拉取至本地&#xff0c;进入项目目录2、执行 npm init 生成json文件3、创建 src/index.ts 入口文件和 src/isObject.ts 工具方法 src/index.ts export { default as isObject } from ./isObject src/isObject.ts /…

Zookeeper 分布式服务协调治理框架介绍入门

文章目录 为甚么需要Zookeeper一、Zookeeper 介绍1.1 介绍1.2 Zookeeper中的一些概念1.2.1 集群角色1.2.2 会话 session1.2.3 数据节点 Znode1.2.4 版本1.2.5 事件监听器 Watcher1.2.6 ACL 权限控制表(Access Control Lists) 二、 Zookeeper的系统模型2.1.1 ZNode节点2.1.2 ZNo…

亿可达:提升工作效能的秘诀

在竞争激烈的职场中&#xff0c;提高工作效率对于个人和团队都至关重要。而选择适合自己的工作效率软件&#xff0c;可以为我们提供更好的工作协作和任务管理体验。下面是我个人推荐的一些实用工作效率软件&#xff0c;希望能对您有所帮助。 1. Any.do&#xff1a;Any.do是一款…

AI小冰入驻淘宝 将提供虚拟人陪伴服务

AI小冰正式入驻淘宝&#xff01; 据悉&#xff0c;小冰在淘宝开出了“小冰旗舰店”、以及手淘小程序“X Eva 克隆人的平行世界”&#xff0c;为消费者提供基于KOL虚拟人带来的陪伴服务体验。用户搜索“小冰旗舰店”就可以直达店铺进行选购。 ​小冰旗舰店的首批商品包括冰花直充…

‘react-native‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。

原因&#xff1a;没有下载react-native 解决下载react-native npm i -g react-native-cli

19|BabyAGI:根据气候变化自动制定鲜花存储策略

19&#xff5c;BabyAGI&#xff1a;根据气候变化自动制定鲜花存储策略 随着 ChatGPT 的崭露头角&#xff0c;我们迎来了一种新型的代理——Autonomous Agents&#xff08;自治代理或自主代理&#xff09;。这些代理的设计初衷就是能够独立地执行任务&#xff0c;并持续地追求长…

使用 Jupyter 分析 ROS 消息时间间隔抖动数据

ROS 是一个分布式机器人操作系统软件框架&#xff0c;节点之间通过松耦合的方式进行组合&#xff0c;包括使用 Topic、RPC 服务和参数服务器等方式进行通信。其中&#xff0c;Topic 是最常见的一种通信方式&#xff0c;例如一个雷达传感器节点实时采集三维点云数据&#xff0c;…

WEB 3D技术 three.js 几何体uv属性讲解与基本演示

本文 我们来说说uv 那么 它是什么呢&#xff1f; 首先 比如 我们几何体 贴一个图 那么 为什么我们图的四个边就能正好贴到几何体的边 为什么不可以图就在几何体中间呢&#xff1f; 中心为什么能对齐 它就不能偏一点吗&#xff1f; 这是第一个问题 还有我们 gltf 这种文件 其实…