Topic:
Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
Problem Solving Ideas:
The previous article has introduced the composition and calculation of Roman numerals, so it is easier to convert Roman numerals into integers.
The way I thought before was to judge the character from left to right and to subtract or other 1,10,100, but it was a lot simpler to see a right-to-left calculation.
When calculating from right to left, it is only necessary to determine whether the current number is not less than 5 or 50,500 when encountering 1,10,100.
C # code:
Public classSolution { Public intRomantoint (strings) {intresult =0; for(inti = s.length-1; I >=0; i--) { Switch(S[i]) { Case 'I': Result+ = (Result >=5) ? -1:1; Break; Case 'V': Result+=5; Break; Case 'X': Result+ = (Result >= -) ? -Ten:Ten; Break; Case 'L': Result+= -; Break; Case 'C': Result+ = (Result >= -) ? - -: -; Break; Case 'D': Result+= -; Break; Case 'M': Result+= +; Break; default: return 0; } } returnresult; }}
View Code
LeetCode-13. Roman to Integer