iT邦幫忙

2021 iThome 鐵人賽

DAY 19
0

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~


12. Integer to Roman

Question

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

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

Example1

Input: num = 3
Output: "III"

Example2

Input: num = 4
Output: "IV"

Example3

Input: num = 9
Output: "IX"

Example4

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

Example5

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

Constraints

  • 1 <= num <= 3999

解題

題目

首先先簡單的翻譯一下題目
給你十進位的數字轉成羅馬數字表示,然後I可以放在VX的前面,X可以放在LC的前面,而C可以放在DM的前面。
像是:IV,V代表的是5,I代表的是1,IV則代表的是4 (5-1),以此類推。

Think

作法大致上是這樣

  • 因為IVIXXLXCCDCM在計算上有點麻煩,所以我就乾脆把他們一起建在dictionary中。
  • keys()是為了要抓到dictionary中最大的數,用來除讀進來的十進位數,再用商來判斷拿來除的羅馬數字應該要有幾個,餘數再拿來除下一輪的dictionary的數。
  • 每次算完,就會把羅馬數字加上去,一直到最後的餘數為0。
  • C的程式睡醒再補上。

Code

Python

class Solution:
    def intToRoman(self, num: int) -> str:
        Symbol_dict = {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'}
        
        roman = ""
        index = -1
        keys = list(Symbol_dict.keys())
        
        while num != 0:
            if num // keys[index] == 0:
                if num % keys[index] == 0:
                    roman = Symbol_dict[keys[index]]
                    return roman
                else:
                    num %= keys[index]
                    index -= 1
            else:
                for times in range(num//keys[index]):
                    roman += Symbol_dict[keys[index]]
                    
                num %= keys[index]
                index -= 1

        return roman

C


Result

  • Python

  • C

大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 18 - Isomorphic Strings
下一篇
Day 20 - Valid Anagram
系列文
30天 Leetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
soft_soft
iT邦新手 5 級 ‧ 2021-10-08 20:38:25

數數字囉3

我要留言

立即登入留言