Description:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
分析:
每次选择能表示的最大值,把对应的字符串连起来
代码:
#include <iostream>
using namespace std;
string IntegerToRoman(int num) {
string str;
string roman[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int integer[]= {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
for(int i=0;num!=0;++i)
{
while(num >= integer[i])
{
num-=integer[i];
str+=roman[i];
}
}
return str;
}
int main()
{
int num1 = 1234;
int num2 = 5678;
int num3 = 923;
cout<<IntegerToRoman(num1)<<endl;
cout<<IntegerToRoman(num2)<<endl;
cout<<IntegerToRoman(num3)<<endl;
return 0;
}
测试: