题目
给定一个整数,将其转换成罗马数字。
返回的结果要求在1-3999的范围内。
4
-> IV
12
-> XII
21
-> XXI
99
-> XCIX
更多案例,请戳 http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
什么是 罗马数字?
解题
拼写规则
I | IV | IX | X | XL | L | XC | C | CD | D | CM | M |
1 | 4 | 5 | 9 | 10 | 40 | 50 | 90 | 100 | 500 | 900 | 1000 |
这样对任一个罗马数字可以 由上面的12个字符进行加法操作完成,即:大数在左,小数在右。《具体为什么,我不是很理解,类似于人民币只有:100,50,20,10,5,2,1,0.5,0.2,0.1可以组成任意金额》
下面程序虽然很差,但是很好理解
public class Solution { /** * @param n The integer * @return Roman representation */ public String intToRoman(int n) { // Write your code here if(n<1 || n>3999) return "ERROR"; String s=""; while(n>=1000){ s += "M"; n -= 1000; } while(n >= 900){ s += "CM"; n -= 900; } while( n>= 500){ s += "D"; n -= 500; } while( n>= 400){ s += "CD"; n -= 400; } while( n >= 100){ s += "C"; n -= 100; } while( n>= 90){ s += "XC"; n -= 90; } while( n>= 50){ s += "L"; n -= 50; } while( n >= 40){ s += "XL"; n -= 40; } while( n>= 10){ s += "X"; n -= 10; } while( n>= 9){ s +="IX"; n -= 9; } while( n>=5 ){ s += "V"; n -= 5; } while( n >= 4 ){ s +="IV"; n -= 4; } while(n >= 1 ){ s +="I"; n -= 1; } return s; } }
然后可以改写成下面的形式
public class Solution { /** * @param n The integer * @return Roman representation */ public String intToRoman(int n) { // Write your code here int[] numbers = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; String[] letters = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; String res ="" ; for(int i = 0;i<13;i++){ if(n >= numbers[i]){ int count = n/numbers[i]; n = n%numbers[i]; for(int j=0;j<count ;j++){ res= res + letters[i]; } } } return res; } }
Python程序也是很简单
class Solution: # @param {int} n The integer # @return {string} Roman representation def intToRoman(self, n): # Write your code here numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1] letters = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] res =[] for i in range(13): if n>= numbers[i]: count = n/numbers[i] n %= numbers[i] res += letters[i]*count return "".join(res)
lintcode 中等题:Integer to Roman 整数转罗马数字
原文:http://www.cnblogs.com/theskulls/p/4957173.html