0
点赞
收藏
分享

微信扫一扫

LeetCode 12. Integer to Roman - 亚马逊高频题15

Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral.

Example 1:

Input: num = 3
Output: "III"
Explanation: 3 is represented as 3 ones.

Example 2:

Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

Example 3:

Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints:

  • 1 <= num <= 3999

题目要求把一个整数转换成罗马数字。罗马数字中没有零和负数,给定整数的范围是[1,3999]。

首先我们需要搞清楚罗马数字是怎么表示的,先以几个数为例,看看它们的罗马数字的表示:

1111->M C X I, 2222->MM, CC, XX, II, 3333->MMM, CCC, XXX, III, 444->CD, XL, IV, 555->D L V, 666->DC, LX, VI, 777->DCC, LXX, VII, 888->DCCC, LXXX, VIII, 999->CM, XC, IV

仔细观察上面的数就会发现个位上的数只由I,V,X组成,十位上的数只由X,L,C组成,百位数上的数只由C,D,M组成,千位上的数由于最大只到3因此只由M;另外一个规律就是各个位上的相同数字构造方式是相同的只是组成的字母不同而已。

因此我们只要实现一个通用函数来转换个位数(1-9)就可以,其它各位数的转换只要调用该通用函数并替换组成的字母即可。跟LeetCode 273. Integer to English Words的思路有点类似。

class Solution:
    def intToRoman(self, num: int) -> str:
        def helper(n, s1, s2, s3):
            if n <= 3:
                return s1 * n
            elif n == 4:
                return s1 + s2
            elif n == 5:
                return s2
            elif n <= 8:
                return s2 + s1 * (n - 5)
            elif n == 9:
                return s1 + s3
            else:
                return s3

        res = ""
        if num > 0:
            res = res + helper(num % 10, "I", "V", "X")
        num //= 10
        if num > 0:
            res = helper(num % 10, "X", "L", "C") + res
        num //= 10
        if num > 0:
            res = helper(num % 10, "C", "D", "M") + res
        num //= 10
        if num > 0:
            res = helper(num % 10, "M", " ", " ") + res
        return res
举报

相关推荐

0 条评论