-
Notifications
You must be signed in to change notification settings - Fork 0
13. Roman to Integer
Jacky Zhang edited this page Aug 2, 2016
·
1 revision
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
String类题目
前一道题的反向操作。 可将String倒序扫描,逐次加和,注意对于4(IV),9(IX),40(XL)等等。 例如:若sum>=5,则'I'表示-1。
public class Solution {
public int romanToInt(String s) {
int num = 0;
for(int i = s.length()-1; i >= 0; i--) {
switch(s.charAt(i)) {
case 'I':
num += (num >= 5? -1 : 1);
break;
case 'V':
num += 5;
break;
case 'X':
num += (num >= 50? -10 : 10);
break;
case 'L':
num += 50;
break;
case 'C':
num += (num >= 500? -100 : 100);
break;
case 'D':
num += 500;
break;
case 'M':
num += 1000;
break;
}
}
return num;
}
}