Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路:罗马数字共有七个,即I(1),V(5),X(10),L(50),C(100),D(500),M(1000)。
第一步,按照千分位,百分位...一一算下来。
class Solution {
public:
string intToRoman(int num) {
int quote;
int residue;
string ret = ""; //first deal with 10^3
quote = num/;
residue = num%;
while(quote > ){
ret += 'M';
quote--;
} //then deal with 10^2
quote = residue/;
residue %= ;
if(quote==){
ret += "CM";
}
else if(quote >=){
ret += 'D';
while(quote > ){
ret += 'C';
quote--;
}
}
else if(quote==){
ret += "CD";
}
else{
while(quote > ){
ret += 'C';
quote--;
}
} //then deal with 10
quote = residue/;
residue %= ;
if(quote==){
ret += "XC";
}
else if(quote >=){
ret += 'L';
while(quote > ){
ret += 'X';
quote--;
}
}
else if(quote==){
ret += "XL";
}
else{
while(quote > ){
ret += 'X';
quote--;
}
} //finally deal with 1
quote = residue;
if(quote==){
ret += "IX";
}
else if(quote >=){
ret += 'V';
while(quote > ){
ret += 'I';
quote--;
}
}
else if(quote==){
ret += "IV";
}
else{
while(quote > ){
ret += 'I';
quote--;
}
} return ret;
}
};
第二步,代码有冗余,将其归纳整合。并且用减法代替除法!
class Solution {
public:
string intToRoman(int num) {
int values[] = {, , , , , , , , , , , , }; //数组的初始化
string numerals[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
int size = sizeof(values) / sizeof(values[]); //获取数组的大小
string result = ""; for (int i = ; i < size; i++) {
while (num >= values[i]) {
num -= values[i];
result+=numerals[i];
}
}
return result;
}
};