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:
Version 1:
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;
}
}
Version 2:
public class Solution {
public static int romanToInt(String s) {
int res = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
switch (c) {
case 'I':
res += (res >= 5 ? -1 : 1);
break;
case 'V':
res += 5;
break;
case 'X':
res += 10 * (res >= 50 ? -1 : 1);
break;
case 'L':
res += 50;
break;
case 'C':
res += 100 * (res >= 500 ? -1 : 1);
break;
case 'D':
res += 500;
break;
case 'M':
res += 1000;
break;
}
}
return res;
}
}