12. Integer to Roman
by Botao Xiao
12. Integer to Roman
Thinking:
- Method1:
Compare and append.
Symbol Value
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
class Solution { public String intToRoman(int num) { if(num <= 0) return ""; String[] roman = {"M", "CM","D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; int[] n = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; StringBuilder sb = new StringBuilder(); for(int i = 0; num != 0; i++){ while(num >= n[i]){ num -= n[i]; sb.append(roman[i]); } } return sb.toString(); } }
Subscribe via RSS