Leetcode | Roman to Integer & Integer to Roman

本文提供了一种简洁的方法来实现罗马数字到整数的转换,同时也介绍了整数到罗马数字的转换算法。通过简单的代码示例,展示了如何在C++中实现这两种转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

搜了一下,才知道这道题可以写这么简洁。

 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         if (s.empty()) return 0;
 5         int dict[100];
 6         dict['I'] = 1; dict['V'] = 5; dict['X'] = 10; dict['L'] = 50;
 7         dict['C'] = 100; dict['D'] = 500; dict['M'] = 1000;
 8     
 9         int ans = dict[s[0]];
10         for (int i = 1; i < s.length(); ++i) {
11             if (dict[s[i]] <= dict[s[i - 1]]) {
12                 ans += dict[s[i]];
13             } else {
14                 ans = ans - 2 * dict[s[i - 1]] + dict[s[i]];
15             }
16         }
17         return ans;
18     }
19 };

Integer to Roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

 1 class Solution {
 2 public:
 3     string intToRoman(int num) {
 4         string str[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
 5         int value[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
 6         
 7         string ret = "";
 8         for (int i = 0; i < 13; ++i) {
 9             while (num >= value[i]) {
10                 ret += str[i];
11                 num -= value[i];
12             }
13         }
14         return ret;
15     }
16 };

 

转载于:https://www.cnblogs.com/linyx/p/3986686.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值