Integer to Roman
LeetCode 12 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Greedy over values including subtractive pairs.
मी 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
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.
मी कसा सोडवला
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'.