LeetCode

[LeetCode] 13. Roman to Integer

2017-05-07  本文已影响0人  xxx亦凡桑

</br>


Given a roman numeral, convert it to an integer.

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


</br>

Solution

The rule for the conversion from roman numeral to integer is

'M' -> 1000
'D' -> 500
'C' -> 100
'L' -> 50
'X' -> 10
'V' -> 5
'I' -> 1

And when smaller number is in front of a bigger number, then smaller number should be subtracted from the latter one.

Hence, we can first translate the roman numeral to normal integer number, and then apply the second rule we mentioned above to determine we should add or minus this particular number.

The code is shown as below.

Java

public class Solution {
    public int romanToInt(String s) {
        
        int string[] = new int[s.length()];
        int sum = 0;
        
        for(int i = 0; i < s.length(); i++){
            switch (s.charAt(i)){
                case 'M':
                    string[i] = 1000;
                    break;
                case 'D':
                    string[i] = 500;
                    break;
                case 'C':
                    string[i] = 100;
                    break;
                case 'L':
                    string[i] = 50;
                    break;
                case 'X' :
                    string[i] = 10;
                    break;
                case 'V':
                    string[i] = 5;
                    break;
                case 'I':
                    string[i] = 1;
                    break;
            }
        }
        
        for(int i = 0; i < string.length-1; i++){
            if(string[i] < string[i+1])
                sum -= string[i];
            else
                sum += string[i];
        }
        
        return sum + string[string.length-1];
    }
}

</br>

上一篇下一篇

猜你喜欢

热点阅读