首页 > 代码库 > Integer to Roman
Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
答案
public class Solution { Map<Integer,Character>mapInt2Char=new HashMap<Integer,Character>(); Map<Integer,Integer>mapLeftInt=new HashMap<Integer,Integer>(); int currentValue[]={1000,500,100,50,10,5,1}; int minValue[]={900,400,90,40,9,4,1}; int maxValue[]={3999,899,399,89,39,8,3}; { mapInt2Char.put( 1,'I'); mapInt2Char.put( 5,'V'); mapInt2Char.put( 10,'X'); mapInt2Char.put( 50,'L'); mapInt2Char.put( 100,'C'); mapInt2Char.put( 500,'D'); mapInt2Char.put( 1000,'M'); } { mapLeftInt.put(1000, 100); mapLeftInt.put(500, 100); mapLeftInt.put(100, 10); mapLeftInt.put(50, 10); mapLeftInt.put(10, 1); mapLeftInt.put(5, 1); } public String intToRoman(int num) { String result=""; if(num<=0) return result; for(int i=0;i<currentValue.length;i++){ if(num>=minValue[i]) { int current=currentValue[i]; if(num==current){ result=""+mapInt2Char.get(current); } else if(num<current){ int left=mapLeftInt.get(current); int dest=num+left-current; result=""+mapInt2Char.get(left)+mapInt2Char.get(current); if(dest>0) { result+=intToRoman(dest); } } else { int dest=num; while(dest>current){ result+=""+mapInt2Char.get(current); dest-=current; } if(dest>0) { result+=intToRoman(dest); } } break; } } return result; } }
Integer to Roman
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。