leetcode-12-Integer-to-Roman

描述


Given an integer, convert it to a roman numeral.

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

分析


这道题和 leetcode-13-Roman-to-Integer 是联系的,罗马数字转换为阿拉伯数字,在 leetcode-13-Roman-to-Integer 中已有介绍,阿拉伯数字转换为罗马数字,可以将罗马字母的值从大到小排列出来,依次对应即可。

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
string intToRoman(int num) {
const int num_list[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
const string symbol[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
string result;

for (int i = 0; num > 0; ++i) {
int count = num / num_list[i];
num %= num_list[i];
for ( ; count > 0; --count) {
result += symbol[i];
}
}
return result;
}
};

解决方案2(Rust)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
impl Solution {
pub fn int_to_roman(num: i32) -> String {
let symble: Vec<(i32, &'static str)> = vec![
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
];

let mut num = num;
let mut result = String::new();
for p in symble.iter() {
if num >= p.0 {
for _ in 0..(num / p.0) {
result.push_str(p.1);
}
num = num % p.0
}
}
result
}
}

相关问题


(E) Roman to Integer
(H) Integer to English Words

题目来源