Roman to Integer

Given a roman numeral, convert it to an integer.

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

Tips:

很傻逼的题。

附了两种做法,但是我根本不知道罗马数字的规则好么!都是O(n)

第一种的解释:

The logic here is that, if a current character value is greater than that of the previous, we have to subtract it. We subtract twice, because previously iteration had blindly added it.

Rule:
BASIC Character
I
V
X
L
C
D
M
Arabic numerals
1
5
10
50
100
500
1000

the rule is complex,but in this condition. It can be tell as:
we start from the end of String.
if the char before the current char we are reading.
plus it
if not
reduce it。

Code:

public class Solution {
    public int romanToInt(String str) {
        int[] a = new int[26];
        a['I' - 'A'] = 1;
        a['V' - 'A'] = 5;
        a['X' - 'A'] = 10;
        a['L' - 'A'] = 50;
        a['C' - 'A'] = 100;
        a['D' - 'A'] = 500;
        a['M' - 'A'] = 1000;
        char prev = 'A';
        int sum = 0;
        for(char s : str.toCharArray()) {
            if(a[s - 'A'] > a[prev - 'A']) {
                sum = sum - 2 * a[prev - 'A'];
            }
            sum = sum + a[s - 'A'];
            prev = s;
        }
        return sum;
    }
}

results matching ""

    No results matching ""