This website describe common assumption and failure during gfg coding.
python
Failed
class Solution: def romanToDecimal(self, s): # code here val={ '':1, 'X':10, 'L':50, 'M':1000, 'C':100, 'V':5 } sum=0 s=s[::-1] count=0 for i in s: if count==1: count=0 sum-=val[i] else: sum+=val[i] count+=1 return sum
Reason
Your current implementation of `romanToDecimal()` has the right spirit, but the logic for subtractive notation (like `IV`, `IX`, `XL`, etc.) is off. You're using a `count` flag, which doesn't reliably detect when subtraction should occur.
---⚠️ Issues:
1. Incorrect subtraction logic: Roman numerals subtract only when a smaller value precedes a larger one.
2. Missing symbols You're missing `'D': 500` in your `val` dictionary.
3. Reversing the string complicates the logic unnecessarily.
---✅ Correct Logic:
- Traverse left to right.
- If the current value is less than the next value → subtract it.
- Otherwise → add it.
✅ Fixed Version:
python
class Solution: def romanToDecimal(self, s): val = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } total = 0 prev = 0 for ch in reversed(s): curr = val[ch] if curr < prev: total -= curr else: total += curr prev = curr return total
🧪 Example:
python
s = "MCMIV"
M = 1000, CM = 900, IV = 4 → Total = 1904
print(Solution().romanToDecimal(s)) # Output: 1904 ✅
Comments
Post a Comment