Problem: Convert a Roman number string into integer. Here are the symbols that Roman numerals used:
- M - 1000
- D - 500
- C - 100
- L - 50
- X - 10
- V - 5
- I - 1
Example:
Input: s = "XIV" Output: 14
Approach: The problem is straight forward we can keep a hash with character to integer mapping and keep adding the value in the hash given the character except where value of next character in the string is more than current character. For example XXV is straight forward and it is (10 + 10 + 5 =) 25 but XXIV is not so straight forward as it is not (10 + 10 + 1 + 5 =) 26, it is 24.
Whenever we see such a pattern where next character value is greater than current character's value. We just add the next character value - current character value into the result and then we jump to next of next character as we have process these two characters. Now if you see XXIV is (10 + 10 + (5 - 1) = ) 24.
That's all!
Implementation in C#:
public int RomanToInt(string s)
{
Dictionary<char, int> hash = new Dictionary<char, int>();
hash['M'] = 1000;
hash['D'] = 500;
hash['C'] = 100;
hash['L'] = 50;
hash['X'] = 10;
hash['V'] = 5;
hash['I'] = 1;
int result = 0;
for (int i = 0; i < s.Length; )
{
int currVal = hash[s[i]];
if (i + 1 < s.Length && hash[s[i + 1]] > hash[s[i]])
{
result += hash[s[i + 1]] - currVal;
i += 2;
}
else
{
result += currVal;
++i;
}
}
return result;
}
Complexity: O(n)
No comments:
Post a Comment