Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Solution:
I = 1;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;
其中每两个阶段的之间有一个减法的表示,比如900=CM, C写在M前面表示M-C。
所以有:I = 1; IV = 4; V = 5; IX = 9; X = 10; XL = 40; L = 50; XC = 90; C = 100; CD = 400; D = 500; CM = 900; M = 1000;
public class Solution { public String intToRoman(int num) { 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}; StringBuilder result = new StringBuilder(); for(int i = 0; i < integer.length; i++) { while(num >= integer[i]) { result.append(roman[i]); num = num - integer[i]; } } return result.toString(); } }
No comments:
Post a Comment