Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解释:罗马数字:I:1
V:5
X:10
L:50
C:100
D:500
M:1000
比如:MCMLXX:1970
MDCLXVI:1666
思路:从高位到低位扫描
可将1970划分为
[M] [CM] [L] [X] [X],即每个段内都是非降序,程序上体现为当出现升序时,减去前一个数字,否则加上前一个数字
class Solution {
public int measure(char c){
if(c=='I'){
return 1;
}else if(c=='V'){
return 5;
}else if(c=='X'){
return 10;
}else if(c=='L'){
return 50;
}else if(c=='C'){
return 100;
}else if(c=='D'){
return 500;
}else if(c=='M'){
return 1000;
}
return 0;
}
public int romanToInt(String s) {
int sum = 0;
int pre = 0;
int temp = 0;
for(int i = 0;i <s.length() ;i++){
temp = measure(s.charAt(i));
if(temp <= pre){
sum += pre;
pre = temp;
}else{
sum -= pre;
pre = temp;
}
}
sum += pre;
return sum;
}
}
最近做点简单的题,偷偷懒......