力扣直通车
问题描述
提示
代码
package com.leetcode.simple;
/**
* @author 花琪尧
* @date 2022/7/29 22:05:27
*/
public class P13_RomanToInt {
public int romanToInt(String s) {
int sum = 0;
if (s.contains("IV")) {
sum += 4;
s = s.replace("IV", "");
}
if (s.contains("IX")) {
sum += 9;
s = s.replace("IX", "");
}
if (s.contains("XL")) {
sum += 40;
s = s.replace("XL", "");
}
if (s.contains("XC")) {
sum += 90;
s = s.replace("XC", "");
}
if (s.contains("CD")) {
sum += 400;
s = s.replace("CD", "");
}
if (s.contains("CM")) {
sum += 900;
s = s.replace("CM", "");
}
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case 'I':
sum += 1;
break;
case 'V':
sum += 5;
break;
case 'X':
sum += 10;
break;
case 'L':
sum += 50;
break;
case 'C':
sum += 100;
break;
case 'D':
sum += 500;
break;
case 'M':
sum += 1000;
break;
default:
System.out.println("输入错误!!!");
System.exit(0);
}
}
return sum;
}
//测试类
public static void main(String[] args) {
P13_RomanToInt rti = new P13_RomanToInt();
System.out.println(rti.romanToInt("LVIII"));
}
}
执行结果
本文含有隐藏内容,请 开通VIP 后查看