Integer to Roman (整数转为罗马数字)
2014-03-27 14:32
513 查看
题目原型:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
基本思路:
题目的意思是给你你一个整数然后把这个整数转为罗马数字形式。例如:1899->MDCCCXCIX,注意:I表示1,V表示5,X表示10,L表示50,C表示100,D表示500,M表示1000.题目比较简单:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
基本思路:
题目的意思是给你你一个整数然后把这个整数转为罗马数字形式。例如:1899->MDCCCXCIX,注意:I表示1,V表示5,X表示10,L表示50,C表示100,D表示500,M表示1000.题目比较简单:
public String intToRoman(int num) { StringBuffer strbuf = new StringBuffer(); Map<Integer,String> map = new HashMap<Integer,String>(); map.put(1 , "I"); map.put(5 , "V"); map.put(10 , "X"); map.put(50 , "L"); map.put(100 , "C"); map.put(500 , "D"); map.put(1000 , "M"); while(num>0) { //求得第一個數字 String numStr = new Integer(num).toString(); int firstNum = numStr.charAt(0)-'0'; int elseNum = 0;//去除第一个数后的余数 int lenOfelseNum = numStr.length()-1;//余数的长度 if(num>=10) elseNum = Integer.parseInt(numStr.substring(1)); int times = (int)Math.pow(10, lenOfelseNum);//倍数 if(map.containsKey(firstNum*times)) { strbuf.append(map.get(firstNum*times)); } else if(firstNum<4) { while(firstNum>0) { strbuf.append(map.get(1*times)); firstNum--; } } else if(firstNum==4||firstNum==9) strbuf.append(map.get(1*times)).append(map.get((firstNum+1)*times)); else if(firstNum>5&&firstNum<9) { strbuf.append(map.get(5*times)); firstNum-=5; while(firstNum>0) { strbuf.append(map.get(1*times)); firstNum--; } } num = elseNum; } return strbuf.toString(); }
相关文章推荐
- leetCode 12.Integer to Roman (整数转罗马数字) 解题思路和方法
- leetcode:Integer to Roman(整数转化为罗马数字)
- [LeetCode] Integer to Roman 整数转化成罗马数字
- Leet Code 13 Roman to Integer - 罗马数字转成整数 - Java
- [LintCode] Roman to Integer 罗马数字转化成整数
- Leet Code 12 Integer to Roman - 整数转成罗马数字 - Java
- Roman to Integer 罗马数字转化为整数
- [Leetcode] Roman to integer 罗马数字转成整数
- LeetCode OJ 之 Integer to Roman (整数转化为罗马数字)
- Roman to Integer 罗马数字转化成整数
- [C++]LeetCode 12: Integer to Roman(将整数转换为罗马数字)
- [LeetCode] Roman to Integer 罗马数字转化成整数
- Roman to Integer 罗马数字转化成整数
- [LeetCode] Roman to Integer 罗马数字转整数
- 【LeetCode-面试算法经典-Java实现】【013-Roman to Integer (罗马数字转成整数)】
- LeetCode | Integer to Roman(整数转换成罗马数字)
- *[lintcode] Integer to Roman 整数转罗马数字
- (LeetCode) Roman to Integer --- 罗马数字转整数
- Roman to Integer---罗马数字转换为十进制整数
- 12:Integer to Roman(数字转为罗马数字)