gpt4 book ai didi

java - 使用递归时如何正确添加字符串

转载 作者:行者123 更新时间:2023-11-30 02:00:09 27 4
gpt4 key购买 nike

我需要一个递归算法来拼出 1 到 21 亿之间的任何数字。我已经整理出了程序的主要部分,但我在将字符串转换为拼写出来的数字时遇到了困难。

例如 1,234,567 次打印:“一千二三四百五六十七”

我明白为什么它在“百万”之前打印“千”,我只是很难找到正确的方法来处理“百”,“千”,“百万”和“十亿”,以便它们以正确的顺序。提前致谢。

static String[] numbers = { "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "ninteen", "twenty"};

static String[] tens = {"twenty-", "thirty-", "fourty-", "fifty-",
"sixty-", "seventy-", "eighty-", "ninety-"};

//static String[] hundreds = {"hundred", "thousand", "million", "billion"};

private static String say(int n) {

if (n <= 20) {
return numbers[n];
}
else if (n < 100) { // 99
return tens[(n / 10) - 2] + say(n % 10); // TODO: fix seventy-zero
}
else if (n < 1000) { // 999 max
return say(n / 100) + " hundred " + say(n % 100);
}
else if (n < 1000000) { // 999,999 max
return say(n / 1000) + " thousand " + say(n % 1000);
}
else if (n < 1000000000) { // 999,999,999 max
return say(n / 1000) + " million " + say(n % 1000);
}
else if (n <= 2147483647) { // 2,147,483,647 max integer value
return say(n / 1000) + " billion " + say(n % 1000);
}
else
return "error";
}

最佳答案

您更新了成百上千的排名但忘了更新百万和十亿的排名。

else if (n < 1000000000) { // 999,999,999 max
return say(n / 1000_000) + " million " + say(n % 1000_000);
}
else if (n <= 2147483647) { // 2,147,483,647 max integer value
return say(n / 1000_000_000) + " billion " + say(n % 1000_000_000);
}

关于java - 使用递归时如何正确添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147727/

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