gpt4 book ai didi

java - 使用递归来反转整数而不使用字符串

转载 作者:行者123 更新时间:2023-12-01 06:30:49 25 4
gpt4 key购买 nike

我已经尝试了一段时间,但无法让它发挥作用。我试图找到一种不使用字符串或数组来反转整数的方法。例如,123 应该反转为整数形式的 321。

我的第一次尝试:

/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
int tempRev = RevDigs(input/10);
if(tempRev >= 10)
reverse = input%10 * (int)Math.pow(tempRev/10, 2) + tempRev;
if(tempRev <10 && tempRev >0)
reverse = input%10*10 + tempRev;
if(tempRev == 0)
reverse = input%10;
return reverse;
}//======================

我也尝试过使用这个,但它似乎弄乱了中间数字:

/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
if(RevDigs(input/10) == 0)
reverse = input % 10;
else
{
if(RevDigs(input/10) < 10)
reverse = (input % 10) *10 + RevDigs(input/10);
else
reverse = (input % 10)* 10 * (RevDigs(input/10)/10 + 1) + RevDigs(input/10);
}
return reverse;
}

我尝试查看网站上的一些示例,但无法让它们正常工作。为了进一步澄清,我不能在这个项目中使用字符串或数组,而必须使用递归。有人可以帮我解决这个问题吗?谢谢。

最佳答案

使用两种方法怎么样

public static long reverse(long n) {
return reverse(n, 0);
}

private static long reverse(long n, long m) {
return n == 0 ? m : reverse(n / 10, m * 10 + n % 10);
}

public static void main(String... ignored) {
System.out.println(reverse(123456789));
}

打印

987654321

关于java - 使用递归来反转整数而不使用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20670444/

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