这是我的阿拉伯语到罗马语的代码:
public class RomanNumeral
{
private static int[] arabics = {1000, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
private static String[] romans = {"M","CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
public static String ArabicToRoman(int arabic)
{
int placeHolder = 0;
String roman = "";
placeHolder = arabic / 1;
for(int i = 0; arabic > 0; i++)
{
placeHolder = arabic / arabics[i];
for(int y = 1; y <= placeHolder; y++)
{
roman = roman + romans[y];
}
arabic = arabic % arabics[i];
}
return roman;
}
我正在寻找一种与此相反的方法,(将罗马语翻译成阿拉伯语),但我似乎无法弄明白。我会喜欢使用相同阵列的一些提示。
答案 0 :(得分:1)
也许是这样的:
private static int[] arabics = {1000, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; private static String[] romans = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; public static int indexOf(String needle, String[]haystack, int length){ int i=-1;while(++i<length&&!(""+haystack.charAt(i)).equals(needle)); return i==length?-1:i; } public static int RomanToArabic(String roman){ int len = roman.length(); int placeHolder[] = new int[len]; for(int i=0;i<len;i++) placeHolder[i]=0; int arabic = 0, k, j=0; for(;j<len-1;j++){ if((k=indexOf(roman.charAt(j)+""+roman.charAt(j+1),romans,13))!=-1) j++; else k=indexOf(roman.charAt(j)+"",romans,13); arabic += arabics[k]; } if(j==len-1)arabic += arabics[indexOf(roman.charAt(j)+"",romans,13)]; return arabic; }