gpt4 book ai didi

java - 将整数转换为罗马数字 - Java

转载 作者:IT老高 更新时间:2023-10-28 20:22:17 25 4
gpt4 key购买 nike

这是我遇到问题的家庭作业。

我需要使用一种方法将整数转换为罗马数字。后来,我必须再用程序用罗马数字写出 1 到 3999,所以硬编码就没有了。我下面的代码非常简单;这是一个基本的 I/O 循环,可以在使用我们在类里面制作的 getIntegerFromUser 包时退出。

有没有办法给字符串赋值,然后在我调用方法时将它们加在一起?

更新:我从教授那里得到了一些伪代码来帮助我,虽然我明白他想说什么,但我在 if 上遇到了一些问题s。我需要很多很多 if 语句,以便我的转换器能够正确处理罗马数字格式,还是有一种方法可以更有效地做到这一点?我更新了我的代码以反射(reflect)我的占位符方法。

更新(2012 年 10 月 28 日):我搞定了。这是我最终使用的:

public static String IntegerToRomanNumeral(int input) {
if (input < 1 || input > 3999)
return "Invalid Roman Number Value";
String s = "";
while (input >= 1000) {
s += "M";
input -= 1000; }
while (input >= 900) {
s += "CM";
input -= 900;
}
while (input >= 500) {
s += "D";
input -= 500;
}
while (input >= 400) {
s += "CD";
input -= 400;
}
while (input >= 100) {
s += "C";
input -= 100;
}
while (input >= 90) {
s += "XC";
input -= 90;
}
while (input >= 50) {
s += "L";
input -= 50;
}
while (input >= 40) {
s += "XL";
input -= 40;
}
while (input >= 10) {
s += "X";
input -= 10;
}
while (input >= 9) {
s += "IX";
input -= 9;
}
while (input >= 5) {
s += "V";
input -= 5;
}
while (input >= 4) {
s += "IV";
input -= 4;
}
while (input >= 1) {
s += "I";
input -= 1;
}
return s;
}

最佳答案

使用 Java 的紧凑实现 TreeMap和递归:

import java.util.TreeMap;

public class RomanNumber {

private final static TreeMap<Integer, String> map = new TreeMap<Integer, String>();

static {

map.put(1000, "M");
map.put(900, "CM");
map.put(500, "D");
map.put(400, "CD");
map.put(100, "C");
map.put(90, "XC");
map.put(50, "L");
map.put(40, "XL");
map.put(10, "X");
map.put(9, "IX");
map.put(5, "V");
map.put(4, "IV");
map.put(1, "I");

}

public final static String toRoman(int number) {
int l = map.floorKey(number);
if ( number == l ) {
return map.get(number);
}
return map.get(l) + toRoman(number-l);
}

}

测试:

public void testRomanConversion() {

for (int i = 1; i<= 100; i++) {
System.out.println(i+"\t =\t "+RomanNumber.toRoman(i));
}

}

关于java - 将整数转换为罗马数字 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12967896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com