标签:style blog color os width io
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对应的罗马数字为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,布布扣,bubuko.com
【leetcode刷题笔记】Integer to Roman
标签:style blog color os width io
原文地址:http://www.cnblogs.com/sunshineatnoon/p/3856057.html