Source From Here
Question
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
For example, two is written as
II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven 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:
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Solution
Naive
Golden (link)
Question
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
- Symbol Value
- I 1
- V 5
- X 10
- L 50
- C 100
- D 500
- M 1000
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:
Example 1:
Example 2:
Example 3:
Example 4:
Example 5:
Solution
Naive
- class Solution:
- def intToRoman(self, num: int) -> str:
- def i2r(d, roman_digits=['I', 'V', 'X']):
- if d < 4:
- return roman_digits[0] * d
- elif d == 4:
- return roman_digits[0] + roman_digits[1]
- elif d == 5:
- return roman_digits[1]
- elif d <= 8:
- return roman_digits[1] + roman_digits[0] * (d - 5)
- else:
- return roman_digits[0] + roman_digits[2]
- roman_level_digits = [['I', 'V', 'X'], ['X', 'L', 'C'], ['C', 'D', 'M'], ['M', '-', '-']]
- roman_num = ''
- level = 0
- while num > 0:
- remainder = num % 10
- roman_num = i2r(remainder, roman_level_digits[level]) + roman_num
- num //= 10
- level += 1
- return roman_num
Golden (link)
- def intToRoman(self, num: int) -> str:
- thousands = ["", "M", "MM", "MMM"]
- hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
- tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
- ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
- return thousands[num // 1000] + hundreds[num % 1000 // 100] + tens[num % 100 // 10] + ones[num % 10]
沒有留言:
張貼留言