首页 > 编程 > Java > 正文

[LeetCode] 12. Integer to Roman java

2019-11-06 06:19:11
字体:
来源:转载
供稿:网友
/**12. Integer to Roman * @param num * @returnString */ public String intToRoman(int num) { int[] n = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] r = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; String ret = ""; for (int i=0; num>0; num=num%n[i], i++) { for(int j = 0, k = num / n[i]; j < k; ++ j) { ret += r[i]; } } return ret; }

//从最大往下找

递归:

public String intToRoman1(int num) { if(num>=1000) return "M"+intToRoman(num-1000); if(num>=900) return "CM"+intToRoman(num-900); if(num>=500) return "D"+intToRoman(num-500); if(num>=400) return "CD"+intToRoman(num-400); if(num>=100) return "C"+intToRoman(num-100); if(num>=90) return "XC"+intToRoman(num-90); if(num>=50) return "L"+intToRoman(num-50); if(num>=40) return "XL"+intToRoman(num-40); if(num>=10) return "X"+intToRoman(num-10); if(num>=9) return "IX"+intToRoman(num-9); if(num>=5) return "V"+intToRoman(num-5); if(num>=4) return "IV"+intToRoman(num-4); if(num>=1) return "I"+intToRoman(num-1); return ""; }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表