题目链接:https://leetcode.com/problems/roman-to-integer/description/
汉字意思大概就是:罗马数字字符串转换为整形数字。想要解决这道题,首先得充分理解罗马数字的特点,可以看百科百科:https://baike.baidu.com/item/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97/772296?fr=aladdin
刚开始我自己对罗马数字特点不熟悉,所以对这道简单的题目一脸懵逼,然后看了下别人提交的答案,找到了两个质量较高的答案吧:
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
System.out.println("romanToInt = " + romanToInt("I") + ", romanToInt2 = " + romanToInt2("I"));
System.out.println("romanToInt = " + romanToInt("X") + ", romanToInt2 = " + romanToInt2("X"));
System.out.println("romanToInt = " + romanToInt("C") + ", romanToInt2 = " + romanToInt2("C"));
System.out.println("romanToInt = " + romanToInt("M") + ", romanToInt2 = " + romanToInt2("M"));
System.out.println("romanToInt = " + romanToInt("III") + ", romanToInt2 = " + romanToInt2("III"));
System.out.println("romanToInt = " + romanToInt("IV") + ", romanToInt2 = " + romanToInt2("IV"));
System.out.println("romanToInt = " + romanToInt("VI") + ", romanToInt2 = " + romanToInt2("VI"));
System.out.println("romanToInt = " + romanToInt("XIX") + ", romanToInt2 = " + romanToInt2("XIX"));
System.out.println("romanToInt = " + romanToInt("XI") + ", romanToInt2 = " + romanToInt2("XI"));
System.out.println("romanToInt = " + romanToInt("XX") + ", romanToInt2 = " + romanToInt2("XX"));
System.out.println("romanToInt = " + romanToInt("XLV") + ", romanToInt2 = " + romanToInt2("XLV"));
System.out.println("romanToInt = " + romanToInt("MCMLXXX") + ", romanToInt2 = " + romanToInt2("MCMLXXX"));
}
public static int romanToInt(String s) {
int sum = 0;
if (s.contains("IV")) {
sum -= 2;
}
if (s.contains("IX")) {
sum -= 2;
}
if (s.contains("XL")) {
sum -= 20;
}
if (s.contains("XC")) {
sum -= 20;
}
if (s.contains("CD")) {
sum -= 200;
}
if (s.contains("CM")) {
sum -= 200;
}
char[] cArr = s.toCharArray();
for (int i = 0; i < cArr.length; i++) {
if (cArr[i] == ‘M‘) {
sum += 1000;
}
if (cArr[i] == ‘D‘) {
sum += 500;
}
if (cArr[i] == ‘C‘) {
sum += 100;
}
if (cArr[i] == ‘L‘) {
sum += 50;
}
if (cArr[i] == ‘X‘) {
sum += 10;
}
if (cArr[i] == ‘V‘) {
sum += 5;
}
if (cArr[i] == ‘I‘) {
sum += 1;
}
}
return sum;
}
public static int romanToInt2(String s) {
int res = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
switch (c) {
case ‘I‘:
res += (res >= 5 ? -1 : 1);
break;
case ‘V‘:
res += 5;
break;
case ‘X‘:
res += 10 * (res >= 50 ? -1 : 1);
break;
case ‘L‘:
res += 50;
break;
case ‘C‘:
res += 100 * (res >= 500 ? -1 : 1);
break;
case ‘D‘:
res += 500;
break;
case ‘M‘:
res += 1000;
break;
}
}
return res;
}
}