Leetcode在线编程 integer-to-roman
题目链接
题目描述
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
题意
将给定的数字转换成罗马数字[1,3999]
解题思路
罗马数字通过
基本字符
I :1
V:5
X:10
L:50
C:100
D:500
M:10001)相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
2)小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
3)小的数字、(限于 Ⅰ、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
4)正常使用时、连写的数字重复不得超过三次;
5)在一个数的上面画一条横线、表示这个数扩大 1000 倍。
剩下来就简单了,通过数组存储个位数,十位数,百位数,千位数,便可以了
AC代码
class Solution {
public:
string intToRoman(int num) {
string tmp;
char one[][10]={"I","II","III","IV","V","VI","VII","VIII","IX"};
char ten[][10]={"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
char hundred[][10]={"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
char thousand[][10]={"M","MM","MMM"};
int cnt = num/1000;
num -= cnt*1000;
if(cnt>=1)
tmp+=thousand[cnt-1];
cnt = num/100;
num -= cnt*100;
if(cnt>=1)
tmp+=hundred[cnt-1];
cnt = num/10;
num -= cnt*10;
if(cnt>=1)
tmp+=ten[cnt-1];
if(num>=1)
tmp+=one[num-1];
return tmp ;
}
};