标签:
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
思路:
这题需要一些背景知识,首先要知道罗马数字是怎么表示的:
http://en.wikipedia.org/wiki/Roman_numerals
I: 1
V: 5
X: 10
L: 50
C: 100
D: 500
M: 1000
字母可以重复,但不超过三次,当需要超过三次时,用与下一位的组合表示:
I: 1, II: 2, III: 3, IV: 4
C: 100, CC: 200, CCC: 300, CD: 400
s = 3978
public class Solution { public String intToRoman(int num) { if(num==0){ return ""; } int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; StringBuilder res=new StringBuilder(); int digit=0; while(num>0){ int times=num/nums[digit]; num=num-times*nums[digit]; for(int i=0; i<times; i++){ res.append(symbols[digit]); } digit++; } return res.toString(); } }
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5339282.html