将罗马数字转换为十进制我设法让我的代码将大多数罗马数字转换为适当的十进制值。但它不适用于某些特殊情况。示例:XCIX= 99但我的代码打印出来109。这是我的代码。public static int romanConvert(String roman){
int decimal = 0;
String romanNumeral = roman.toUpperCase();
for(int x = 0;x<romanNumeral.length();x++)
{
char convertToDecimal = roman.charAt(x);
switch (convertToDecimal)
{
case 'M':
decimal += 1000;
break;
case 'D':
decimal += 500;
break;
case 'C':
decimal += 100;
break;
case 'L':
decimal += 50;
break;
case 'X':
decimal += 10;
break;
case 'V':
decimal += 5;
break;
case 'I':
decimal += 1;
break;
}
}
if (romanNumeral.contains("IV"))
{
decimal-=2;
}
if (romanNumeral.contains("IX"))
{
decimal-=2;
}
if (romanNumeral.contains("XL"))
{
decimal-=10;
}
if (romanNumeral.contains("XC"))
{
decimal-=10;
}
if (romanNumeral.contains("CD"))
{
decimal-=100;
}
if (romanNumeral.contains("CM"))
{
decimal-=100;
}
return decimal;}
3 回答
人到中年有点甜
TA贡献1895条经验 获得超7个赞
如果你反过来走路会很好。
public class RomanToDecimal { public static void romanToDecimal(java.lang.String romanNumber) { int decimal = 0; int lastNumber = 0; String romanNumeral = romanNumber.toUpperCase(); /* operation to be performed on upper cases even if user enters roman values in lower case chars */ for (int x = romanNumeral.length() - 1; x >= 0 ; x--) { char convertToDecimal = romanNumeral.charAt(x); switch (convertToDecimal) { case 'M': decimal = processDecimal(1000, lastNumber, decimal); lastNumber = 1000; break; case 'D': decimal = processDecimal(500, lastNumber, decimal); lastNumber = 500; break; case 'C': decimal = processDecimal(100, lastNumber, decimal); lastNumber = 100; break; case 'L': decimal = processDecimal(50, lastNumber, decimal); lastNumber = 50; break; case 'X': decimal = processDecimal(10, lastNumber, decimal); lastNumber = 10; break; case 'V': decimal = processDecimal(5, lastNumber, decimal); lastNumber = 5; break; case 'I': decimal = processDecimal(1, lastNumber, decimal); lastNumber = 1; break; } } System.out.println(decimal); } public static int processDecimal(int decimal, int lastNumber, int lastDecimal) { if (lastNumber > decimal) { return lastDecimal - decimal; } else { return lastDecimal + decimal; } } public static void main(java.lang.String args[]) { romanToDecimal("XIV"); }}
倚天杖
TA贡献1828条经验 获得超3个赞
假设哈希看起来像这样
Hashtable<Character, Integer> ht = new Hashtable<Character, Integer>(); ht.put('i',1); ht.put('x',10); ht.put('c',100); ht.put('m',1000); ht.put('v',5); ht.put('l',50); ht.put('d',500);
然后逻辑变得非常简单,从右到左依次为数字
public static int rtoi(String num){ int intNum=0; int prev = 0; for(int i = num.length()-1; i>=0 ; i--) { int temp = ht.get(num.charAt(i)); if(temp < prev) intNum-=temp; else intNum+=temp; prev = temp; } return intNum;}
添加回答
举报
0/150
提交
取消