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'.