Click to view the answer
Subtract "the value of the previous character * 2".
## Complexity
- Time complexity: `O(N)`.
- Space complexity: `O(1)`.
## Ruby
```ruby
# @param {String} s
# @return {Integer}
def roman_to_int(s)
char_to_num = {
"I" => 1,
"V" => 5,
"X" => 10,
"L" => 50,
"C" => 100,
"D" => 500,
"M" => 1000,
}
result = 0
s.chars.each_with_index do |c, i|
result += char_to_num[c]
next if i == 0
if char_to_num[s[i - 1]] < char_to_num[c]
result -= char_to_num[s[i - 1]] * 2
end
end
result
end
```
## Python
```python
class Solution:
def romanToInt(self, s: str) -> int:
char_to_num = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
result = 0
for i, c in enumerate(s):
result += char_to_num[c]
if i == 0:
continue
# If the previous value is smaller than the current,
# subtract it twice (once because it was added, once for the rule)
if char_to_num[s[i - 1]] < char_to_num[c]:
result -= char_to_num[s[i - 1]] * 2
return result
```
## Java
```java
class Solution {
public int romanToInt(String s) {
Map