leetcode_Integer to Roman
描写叙述:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路:
1.因为罗马数字是字符的形式堆叠而成的,所以最好还是将数字的每一位转换成字符并结合对应的量级合成罗马字符串
2.对应的,对于每一个字符数字在不考虑量级的情况下大概分三种情况能够解决阿拉伯数字到罗马数字的转换。分(number>=1&&number<=3)、(number>=4&&number<=8)、(number==9)来考虑,详细的实现见代码。
代码:
public String intToRoman(int num) { StringBuilder sBuilder=new StringBuilder(); char chArr[] ={ 'I', 'V', 'X', 'L', 'C', 'D', 'M' }; int numArr[] ={ 1, 5, 10, 50, 100, 500, 1000 }; HashMap<Integer,Character> map = new HashMap< Integer,Character>(); HashMap<Character, Integer> priorityMap = new HashMap<Character, Integer>(); for (int i = 0; i < chArr.length; i++) { map.put(numArr[i], chArr[i]); priorityMap.put(chArr[i], i); } String numString=String.valueOf(num); int tempNum=1; int number=0; int numLen=numString.length(); for(int i=1;i<numLen;i++) tempNum*=10; char ch='0'; for(int i=0;i<numLen;i++) { number=numString.charAt(i)-'0'; if(number>=1&&number<=3) { ch=map.get(tempNum); for(int j=0;j<number;j++) sBuilder.append(ch); } else if(number>=4&&number<=8) { ch=map.get(tempNum); int pri=priorityMap.get(ch); char newChar=chArr[pri+1]; for(int j=0;j<5-number;j++) sBuilder.append(ch); sBuilder.append(newChar); for(int j=6;j<=number;j++) sBuilder.append(ch); }else if(number==9) { ch=map.get(tempNum); int pri=priorityMap.get(ch); char newChar=chArr[pri+2]; sBuilder.append(ch); sBuilder.append(newChar); } tempNum/=10; } return sBuilder.toString(); }
posted on 2017-06-09 10:32 cynchanpin 阅读(144) 评论(0) 编辑 收藏 举报