# CLEAN CODE | GIVEN A ROMAN NUMERAL, CONVERT IT TO AN INTEGER.| STRING | PATTERN QUESTIONS

By: Saurav

2018-02-10 03:20:00 UTC

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Read more details about roman numerals at Roman Numeric System

Example :

Input : "XIV"
Return : 14
Input : "XX"
Output : 20

InterviewBit

This problem is simple if you can see the pattern. The pattern to follow is:
In an iteration, see if the next element is greater than the current element, subtract the current element from net sum
else add the element to the net sum.

lets see it in action:

```def roman_to_integer(string)
return 0 if string.length < 1
dictionary = {"I" => 1, "V" => 5, "X" => 10, "L" => 50, "C" => 100, "D" => 500, "M" => 1000}

sum = 0

(0..string.length-2).each do |i|
if dictionary[string[i]] >= dictionary[string[i+1]]
sum += dictionary[string[i]]
else
sum -= dictionary[string[i]]
end
end

sum += dictionary[string[-1]]

return sum
end
```

Owned & Maintained by Saurav Prakash

If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :) 