[LeetCode] 12. Integer to Roman 整数转为罗马数字
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
将阿拉伯整数转为罗马数字,首先要对罗马数字有了解,找到两种数字转换的规律,然后用一个Hash map来保存这些规律,然后把整数进行相应的转换。输入数字的范围(1 - 3999)。
Python:
class Solution(object): def intToRoman(self, num): """ :type num: int :rtype: str """ numeral_map = {1: "I", 4: "IV", 5: "V", 9: "IX", \ 10: "X", 40: "XL", 50: "L", 90: "XC", \ 100: "C", 400: "CD", 500: "D", 900: "CM", \ 1000: "M"} keyset, result = sorted(numeral_map.keys()), [] while num > 0: for key in reversed(keyset): while num / key > 0: num -= key result += numeral_map[key] return "".join(result)
C++:
class Solution { public: string intToRoman(int num) { const vector<int> nums{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; const vector<string> romans{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; string result; int i = 0; while (num > 0) { int times = num / nums[i]; while (times--) { num -= nums[i]; result.append(romans[i]); } ++i; } return result; } };
类似题目:
[LeetCode] 13. Roman to Integer 罗马数字转为整数
相关推荐
嗡汤圆 2020-05-10
txlCandy 2019-03-27
shishengsoft 2019-09-02
zhglinux 2019-06-29
zangdaiyang 2019-06-21
heysakura 2018-04-17
胖胖雕的GIS 2017-04-19
lispython 2019-02-25
PlatformThinking 2018-02-07