(LeetCode) 12. Integer to Roman

文章目录

  1. 1. Original URL: 12. Integer to Roman
  2. 2. My solutions:
    1. 2.1. With C++:

Given an integer, convert it to a roman numeral.

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

Difficulty: Medium
Tags: Math, String

Original URL: 12. Integer to Roman

My solutions:

With C++:

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
32
33
34
class Solution {
public:
string intToRoman(int num) {
int S = num / 1000;
int H = num / 100 % 10;
int T = num / 10 % 10;
int L = num % 10;
string S_str, H_str, T_str, L_str, Roam="";
S_str.append(S,'M');
H_str = ToRoam(H,'C','D','M');
T_str = ToRoam(T,'X','L','C');
L_str = ToRoam(L,'I','V','X');
Roam += S_str + H_str +T_str + L_str;
return Roam;
}
private:
string ToRoam(int t, char O, char P, char Q){
string str = "";
if(t == 9)
{str += O;
str += Q;}
else if(t >= 5)
{
str += P;
str.append(t-5,O);
}
else if(t < 4)
{str.append(t,O);}
else
{str += O;
str += P;}
return str;
}
};

See my 30+ solutions of LeetCode on GitHub