题目详情
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.题目的意思是: 输入一个阿拉伯数字,我们需要输出这个数字的罗马数字表示形式(字符串)。
想法
- 这道题最重要的点就是理解罗马数和阿拉伯数之间的转换规律。
- 1000[M],500[D],100[C],50[L],10[X],5[V],1[I]这是基本转换
- 但是还有一些特殊情况900[CM]:这种情况就是左边的这个罗马字符代表的数、减去右边的这个罗马字符代表的数才得到900。相似的有400[CD],90[XC],40[XL],9[IX],4[IV]
解法
public String intToRoman(int num) { if(num < 1)return ""; int[] numbers = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; String[] roman = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; StringBuilder res = new StringBuilder(); for(int i=0;i= numbers[i]){ num -= numbers[i]; res.append(roman[i]); } } return res.toString(); }