本文主要是介绍96. Integer to Roman,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
分析:将一个数字转化为罗马字符串表示。
大数左边加上小数就是把大数减去这个小数."M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"分别对应1000,900,500,400,100,90,50,40,10,9,5,4,1。以最左边为最大的字符为原则,从大到小判断num的值。
/*** 将一个数字转化为罗马字符串表示。* 大数左边加上小数就是把大数减去这个小数.I(1),V(5),X(10),L(50),C(100),D(500),M(1000)。* 以最左边为最大的字符为原则,从大到小判断num的值。*/public String intToRoman(int num) {StringBuffer sb = new StringBuffer();String symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int value[]= {1000,900,500,400,100,90,50,40,10,9,5,4,1}; int i=0;while(num!=0){while(num>=value[i]){/*先从罗马数字可以表示的最大值开始依次往后换算*/sb.append(symbol[i]);num=num-value[i];}i++;}return new String(sb);}
这篇关于96. Integer to Roman的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!