我想找到最簡單的算法來隱藏羅馬數字int.I有這個代碼從羅塞塔代碼,但有代碼中沒有什麼意義的東西很少。羅馬數字整數
在以下代碼的for循環中羅馬數字是如何迭代的?可以在任何解釋如何嵌套的for循環在這裏工作或者你有寫這個算法
public class Roman {
enum Numeral {
I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
int weight;
Numeral(int weight) {
this.weight = weight;
}
};
public static String roman(long n) {
if(n <= 0) {
throw new IllegalArgumentException();
}
StringBuilder buf = new StringBuilder();
final Numeral[] values = Numeral.values();
for (int i = values.length - 1; i >= 0; i--) {
while (n >= values[i].weight) {
buf.append(values[i]);
n -= values[i].weight;
}
}
return buf.toString();
}
public static void test(long n) {
System.out.println(n + " = " + roman(n));
}
public static void main(String[] args) {
test(1999);
test(25);
test(944);
test(0);
}
除非您向後回答您的問題,否則此枚舉用於將整數轉換爲羅馬數字,而不是將羅馬數字轉換爲整數。 – 2016-01-21 19:21:20
[將羅馬數字轉換爲十進制]可能的重複(http://stackoverflow.com/questions/9073150/converting-roman-numerals-to-decimal) – 2016-01-21 19:23:21