Integer to Roman : https://leetcode.com/problems/integer-to-roman/
degree : Medium
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字的拼写规则:详细拼写规则,见最后附录。
1, 4, 5, 9, 10, 19
I, IV, V, IX, X, XIX
注:9 不可写成 VIIII 只能最多存在连续3个,也不可写成 VIV,只能写成IX
因此可想到必须分4和9特出处理
#include <string>
#include <iostream>
using namespace std;
//I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000),不能有连续4个
class Solution {
public:
string intToRoman(int num) {
if (num < 1 || num > 3999)
return NULL;
string s;
int d[4] = {1000, 100, 10, 1};
for (int i = 0; num > 0 && i < 4; i++) {
int r = num / d[i];//共有几个
char c = intToRomanChar(d[i]);
if (r == 0) {
continue;
} else if (r > 0 && r < 4) {
for (int j = 0; j < r; j++)
s.push_back(c);
} else if (r == 4) {
s.push_back(c); //小的在前
s.push_back(intToRomanChar(d[i]*5)); //大的在后
} else if (r > 4 && r < 9) {
s.push_back(intToRomanChar(d[i]*5)); //大的在前
for (int j = 5; j < r; j++)
s.push_back(intToRomanChar(d[i])); //小的在后
} else if (r == 9) {
s.push_back(intToRomanChar(d[i]));
s.push_back(intToRomanChar(d[i-1]));
}
num %= d[i];
}
return s;
}
private:
char intToRomanChar(int d) {
switch (d) {
case 1:
return ‘I‘;
case 5:
return ‘V‘;
case 10:
return ‘X‘;
case 50:
return ‘L‘;
case 100:
return ‘C‘;
case 500:
return ‘D‘;
case 1000:
return ‘M‘;
}
}
};
int main()
{
int n;
Solution sol;
while (1)
{
cin >> n;
cout << sol.intToRoman(n) << endl;
}
}
根据以上程序,可以观察到4,9对应特殊,因此可得到以下简化的实现过程,相当于扩展Roman数字的拼写规则
#include <string>
#include <iostream>
using namespace std;
//I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000),不能有连续4个
class Solution {
public:
string intToRoman(int num) {
if (num < 1 || num > 3999)
return NULL;
string s;
const int d[] = {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"};
for (int i = 0; num > 0 && i < sizeof(d)/sizeof(d[0]); i++) {
int r = num / d[i];
for (int j = 0; j < r; j++)
s += symbol[i];
num %= d[i];
}
return s;
}
};
int main()
{
int n;
Solution sol;
while (1)
{
cin >> n;
cout << sol.intToRoman(n) << endl;
}
}
罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。按照下述的规则可以表示任意正整数。需要注意的是罗马数字中没有“0”,与进位制无关。一般认为罗马数字只用来记数,而不作演算。
原文地址:http://blog.csdn.net/quzhongxin/article/details/45718541