I found a Leet code problem which involved converting a string of Roman Numerals to Normal Integers and a friend of mine told me that using a ** Hashmap and a reverse for loop ** is best in an issue like this, although using simple arithmetic operations, I solved the problem.
Can someone explain how it works better in that scenario? Thank you in advance.
class Solution:
def romanToInt(self, s: str) -> int:
answer = 0
answer = (s.count('M') * 1000) + (s.count('C') * 100) + (s.count('X') * 10) + (s.count('I') * 1)
answer += (s.count('D') * 500) + (s.count('L') * 50) + (s.count('V') * 5)
answer -= (s.count('CM') * 200) + (s.count('XC') * 20) + (s.count('IX') * 2)
answer -= (s.count('CD') * 200) + (s.count('XL') * 20) + (s.count('IV') * 2)
return answer