題目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
題解:
這道題跟interger to roman一樣都得先熟悉羅馬數字的規則。羅馬數字的規則我在integer to roman里面寫了,可以參考那個。
從后往前檢查string,全局維護一個res來記錄。
代碼如下:
1
public
static
int romanToInt(String s) {
2 int res = 0;
3 for ( int i = s.length() - 1; i >= 0; i--) {
4 char c = s.charAt(i);
5 if(c == 'I'){
6 if(res >= 5) // 如果>=5, 說明之前肯定遍歷過V了,所以這個I肯定在左邊,減
7 res += -1;
8 else
9 res += 1;
10 } else if(c == 'V'){ // 遇見V,L,D,M,統統都加5,50,500,100
11 res += 5;
12 } else if(c == 'X'){
13 if(res >= 50) // 說明肯定之前有過L,這個X肯定在左邊,減
14 res += -10;
15 else
16 res += 10;
17 } else if(c == 'L'){
18 res += 50;
19 } else if(c == 'C'){ // 說明之前有D,這個C肯定在左邊,減。能被減的只有I X C
20 if(res >= 500)
21 res += -100;
22 else
23 res += 100;
24 } else if(c == 'D'){
25 res += 500;
26 } else if(c == 'M'){
27 res += 1000;
28 }
29 }
30 return res;
31 }
2 int res = 0;
3 for ( int i = s.length() - 1; i >= 0; i--) {
4 char c = s.charAt(i);
5 if(c == 'I'){
6 if(res >= 5) // 如果>=5, 說明之前肯定遍歷過V了,所以這個I肯定在左邊,減
7 res += -1;
8 else
9 res += 1;
10 } else if(c == 'V'){ // 遇見V,L,D,M,統統都加5,50,500,100
11 res += 5;
12 } else if(c == 'X'){
13 if(res >= 50) // 說明肯定之前有過L,這個X肯定在左邊,減
14 res += -10;
15 else
16 res += 10;
17 } else if(c == 'L'){
18 res += 50;
19 } else if(c == 'C'){ // 說明之前有D,這個C肯定在左邊,減。能被減的只有I X C
20 if(res >= 500)
21 res += -100;
22 else
23 res += 100;
24 } else if(c == 'D'){
25 res += 500;
26 } else if(c == 'M'){
27 res += 1000;
28 }
29 }
30 return res;
31 }