题目
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
思路
题目要求把1-3999的整数转换为罗马数字。只要找出罗马数字各位上的规律,就可以很方便地解出了。个位上的罗马数字(1-9)为'I','II','III','IV','V','VI','VII','VIII','IX'],十位上的罗马数字(1-9)为['X','XX','XXX','XL','L','LX','LXX','LXXX','XC'],百位上的罗马数字(1-9)为['C','CC','CCC','CD','D','DC','DCC','DCCC','CM'],千位上1-3分别为M、MM、MMM。
按照这个规律只需要四个字符串列表即可实现转换。
(PS:个人觉得这是刷LeetCode目前为止最简单的一道题)
代码
Python
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
if (num < 1) or (num > 3999):
return None
thousand = num / 1000
hundred = (num / 100)%10
ten = (num / 10)%10
one = num%10
rTh = ['','M','MM','MMM']
rHun = ['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM']
rTen = ['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC']
rOne = ['','I','II','III','IV','V','VI','VII','VIII','IX']
return rTh[thousand]+rHun[hundred]+rTen[ten]+rOne[one]
Java
public class Solution {
public String intToRoman(int num) {
if (num < 1 || num > 3999) return null;
int thousand = num / 1000;
int hundred = (num / 100)%10;
int ten = (num / 10)%10;
int one = num%10;
String[] rTh = {"","M","MM","MMM"};
String[] rHun = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
String[] rTen = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
String[] rOne = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
return rTh[thousand]+rHun[hundred]+rTen[ten]+rOne[one];
}
}