class Solution {
public int romanToInt(String s) {
int ans = 0;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(i < s.length() - 1){
if(ch == 'C' && (s.charAt(i + 1) == 'M' || s.charAt(i + 1) == 'D')){
ans -= 200;
}
if(ch == 'X' && (s.charAt(i + 1) == 'C' || s.charAt(i + 1) == 'L')){
ans -= 20;
}
if(ch == 'I' && (s.charAt(i + 1) == 'X' || s.charAt(i + 1) == 'V')){
ans -= 2;
}
}
ans += getValue(ch);
}
return ans;
}
private int getValue(char ch) {
switch(ch) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
}
13. 罗马数字转整数
最新推荐文章于 2025-02-10 21:22:44 发布