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 |
每隔一个字符又可以与相邻的两个字符组成一个新的数,例如I可以和V和X组成IV和IX,这样又可以生成6个数字,如下表:
罗马字符 | 数字 |
IV | 4 |
IX | 9 |
XL | 40 |
XC | 90 |
CD | 400 |
CM | 900 |
接下来我们用numbers记录上述13个数字,symbol数组记录上述13个符号,然后从最大的数1000开始,一步步将num转换成数字。
数字3012的转换过程如下:
- 3012/1000 = 3,answer = MMM,num <- 3012-3000=12;
- 12/900=0; 12/500 = 0; ......
- 12/10 = 1, answer = MMM+X=MMMX, num <- 12 - 10 = 2;
- 2/9 = 0,; 2/5 = 0; 2/4 = 0;
- 2/1 = 2, answer = MMMX+II = MMMXII, num <- 2-2 = 0;
所以3012对应的罗马数字为MMMXII。
代码如下:
1 public class Solution { 2 public String intToRoman(int num) { 3 if(num <= 0) 4 return ""; 5 6 int[] numbers = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; 7 String[] symbol = {"M","CM","D","CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 8 9 StringBuffer answer = new StringBuffer(); 10 int digit = 0; 11 while(num > 0){ 12 int times = num / numbers[digit]; 13 for(int i = 0;i < times;i++) 14 answer.append(symbol[digit]); 15 num = num - numbers[digit] * times; 16 digit++; 17 } 18 return answer.toString(); 19 } 20 }
【leetcode刷题笔记】Integer to Roman
时间: 2024-10-27 09:47:32