Hello everyone!
There is this leetcode challenge which is to convert roman numbers to integers.
This is a beginner level problem I tried to solve and it was fun.
You can try it before continuing with the post. Maybe you might come up with an efficient solution as well.
Photo by Mathew Schwartz
Hope you are now familiar with the problem.
Let's see our function that returns according integers.
GetInteger(string roman)
switch (roman)
{
case "I": return 1;
case "V": return 5;
case "X": return 10;
case "L": return 50;
case "C": return 100;
case "D": return 500;
case "M": return 1000;
default: return -1;
}
Call it and output should give accurate results.
But what if this input that is a string called roman was not a single letter? As an example "IX".
If so the case should jump to default case and it has to be resolved.
First let's make the input string a char array.
char[] characters = roman.ToCharArray();
- We assign the returning value as the integer value of last letter.
number -> 'X' -> 10
We are going to iterate from one before last to first of this char array.
We take the current value as the integer value of current char.
current -> 'I' -> 1
- We take the previous value as the integer value of char to the right of the current char.
previous -> 'X' -> 10
- We add or subtract returning value if current value becomes more or less than the previous value.
current -> 1, previous -> 10, previous > current -> yes
number -> previous - current -> 9
Therefore the returned value for IX becomes 9.
This applies for any roman number given.
Source code below.
public static int GetInteger(char c)
{
switch (c)
{
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return -1;
}
}
public static int RomanToInt(string s)
{
char[] characters = s.ToCharArray();
int number = GetInteger(characters[characters.Length - 1]);
for (int i=characters.Length-2, previousValue, currentValue; i>=0; i--)
{
currentValue = GetInteger(characters[i]);
previousValue = GetInteger(characters[i + 1]);
number = previousValue > currentValue
? number - currentValue
: number + currentValue;
}
return number;
}
Thanks for reading!
Top comments (0)