Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 12 · Sorting + Simple Greedy

Integer to Roman

LeetCode 12 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Greedy over values including subtractive pairs.

మధ్యస్థంHash TableMathString
LeetCode లో తెరవండి ↗

నేను Integer to Roman (LeetCode 12) ను ఇలా పరిష్కరించాను — Sorting + Simple Greedy ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Roman numerals are greedy: always write the largest symbol that still fits. Including the six subtractive pairs (CM, CD, XC, XL, IX, IV) in the table makes the greedy rule produce the correct form.

Approach

  1. 1

    Table of 13 values from 1000 down to 1.

  2. 2

    While num > 0, append each symbol as many times as it fits.

  3. 3

    Subtract its value each time.

నేను ఎలా పరిష్కరించాను

Greedy tablePythonO(1) time
class Solution:
    def intToRoman(self, num: int) -> str:
        nums = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
        symbols = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
        ans = ""
        while num>0:
            for index,cur_num in enumerate(nums):
                while cur_num<=num:
                    ans+=symbols[index]
                    num=num-cur_num
                    if cur_num>num:
                        break;
        return ans
స్టెప్-త్రూ లోడ్ అవుతోంది…

Integer to Roman — తరచూ అడిగే ప్రశ్నలు

Integer to Roman వెనుక ఉన్న intuition ఏమిటి?

Roman numerals are greedy: always write the largest symbol that still fits. Including the six subtractive pairs (CM, CD, XC, XL, IX, IV) in the table makes the greedy rule produce the correct form.

Integer to Roman (LeetCode 12) ను ఎలా పరిష్కరించాలి?

1. Table of 13 values from 1000 down to 1. 2. While num > 0, append each symbol as many times as it fits. 3. Subtract its value each time.

Integer to Roman యొక్క time, space complexity ఎంత?

Time: O(1). Space: O(1). (Accepted approach: Greedy table.)

Integer to Roman లో సాధారణ పొరపాట్లు ఏమిటి?

Without CM, XC, IV, etc. you'd produce 'VIIII'.