Integer to Roman

来源:互联网 发布:centos 6.5搭建lnmp 编辑:程序博客网 时间:2024/05/18 18:46
题目:Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

罗马数字有自己的组合规则,最简单的方法就是将其1-9,

10-90,100-900,1000-3000的写法放在数组中,通过判断

数字调用数组中的元素组合起来就是想要的罗马数字。

public static String intToRoman(int num) {String c[][] = {{ "0", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" },{ "0", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" },{ "0", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" },{ "0", "M", "MM", "MMM" } };int tmp = num;StringBuffer st = new StringBuffer();if(tmp/1000!=0)st.append(c[3][tmp/1000]);if(tmp%1000/100!=0)st.append(c[2][tmp%1000/100]);if(tmp%100/10!=0)st.append(c[1][tmp%100/10]);if(tmp%10!=0)st.append(c[0][tmp%10]);return st.toString();}

更简单的方法是:

public static String intToRoman(int num) {String c[][] = {{ "0", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" },{ "0", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" },{ "0", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" },{ "0", "M", "MM", "MMM" } };int digit = 0,temp=0;String st="";while(num!=0){temp=num%10;st=c[digit][temp]+st;digit++;num/=10;}return st;}



0 0
原创粉丝点击