leetcode12 Integer to Roman
2015-01-27 19:47
507 查看
这个题目是把1~3999之间的整数转换为罗马数字。首先列举一下几个基本的罗马数字,1---I,5---V,10---X,50---L,100---C,500---D,1000---M。其他的罗马数字都是由这几个组成的。一个较小的单位连在较大单位前面,表示后面的减去前面的,比如CM即为900,XL即为40。我自己写了一个方法,但是比较笨拙,如下所示:
在网上看了看别人的代码,写的都很好,而且扩展性很强
public String intToRoman(int num) { Map map=new HashMap(); map.put(1, "I"); map.put(2, "II"); map.put(3, "III"); map.put(4, "IV"); map.put(5, "V"); map.put(6, "VI"); map.put(7, "VII"); map.put(8, "VIII"); map.put(9, "IX"); map.put(10, "X"); map.put(20, "XX"); map.put(30, "XXX"); map.put(40, "XL"); map.put(50, "L"); map.put(60, "LX"); map.put(70, "LXX"); map.put(80, "LXXX"); map.put(90, "XC"); map.put(100, "C"); map.put(200, "CC"); map.put(300, "CCC"); map.put(400, "CD"); map.put(500, "D"); map.put(600, "DC"); map.put(700, "DCC"); map.put(800, "DCCC"); map.put(900, "CM"); map.put(1000, "M"); map.put(2000, "MM"); map.put(3000, "MMM"); if(num<1 || num>3999){ return null; } StringBuffer sb=new StringBuffer(); int number=num; int count=1; while(number/10 !=0){ //计算num有几位 count++; number=number/10; } for(int i=count;i>0;i--){ int next=num%(int)Math.pow(10, i-1); int temp=num-next; if(temp!=0){ sb.append(map.get(temp)); } num=next; } return sb.toString(); }
在网上看了看别人的代码,写的都很好,而且扩展性很强
public String intToRoman1(int num) { String[] str = new String[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; int[] val = new int[] { 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 >= val[i]) { num -= val[i]; sb.append(str[i]); } } return sb.toString(); }
相关文章推荐
- [leetcode 12] Integer to Roman
- Leetcode_12_Integer to Roman
- LeetCode 12 - Integer to Roman
- [Leetcode] 12. Integer to Roman
- [Leetcode 44] 12 Integer To Roman
- LeetCode --- 12. Integer to Roman
- LeetCode12: Integer to Roman
- Leetcode 12 Integer to Roman整数变罗马
- leetcode 12 Integer to Roman
- [Leetcode] 12 - Integer to Roman
- LeetCode 12 integer to roman
- [LeetCode]12.Integer to Roman
- LeetCode 12 Integer to Roman(C,C++,Java,Python)
- [LeetCode]12 Integer to Roman
- Integer to Roman_Leetcode_#12
- [LeetCode 12] Integer to Roman
- 12. Integer to Roman Leetcode Python
- [C++]LeetCode 12: Integer to Roman(将整数转换为罗马数字)
- LeetCode 12 - Integer to Roman
- LeetCode12~14 Integer to Roman/Roman to Integer/Longest Common Prefix