Programming Question — Leetcode 13
Approach to solve leetcode 13 question — Roman to Integer
- There can be two conditions in this question, first is if it is a normal number like ‘III’ or ‘XX’ or ‘V’ , we just keep adding corresponding integer number of that character.
- or there can be characters like ‘IV’(4) or ‘XLIV’(44). In these kind of characters we can see that if we generally add all characters they will become like :
I + V = 6 (but it is actually 4) or X+L+I+V = 10+50+1+5 = 66(but it is actually 44)
in these examples we see that if previous character is smaller than its next character then we can not just add them normally, instead we have to do as:
I + V = 6 , we can do (current value — 2*previous value) so it will become
6–2*1 = 4 (which is correct ) same as X+L = 60 but (60–2*10) is 50 which is correct.
3. So we will iterate through the string and keep adding value in the total and return total at the end.