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

0 java recursion integer

我已经尝试了一段时间但是无法让它发挥作用.我试图有一个方法来反转整数而不使用字符串或数组.例如,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;
}//======================
Run Code Online (Sandbox Code Playgroud)

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

/** 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;
}
Run Code Online (Sandbox Code Playgroud)

我试过看一下网站上的一些例子,但是我无法让它们正常工作.为了进一步说明,我不能为这个项目使用String或数组,并且必须使用递归.有人可以帮我解决问题.谢谢.

Pet*_*rey 6

如何使用两种方法

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));
}
Run Code Online (Sandbox Code Playgroud)

版画

987654321
Run Code Online (Sandbox Code Playgroud)


Mic*_*bak 5

关于什么:

public int RevDigs(int input) {
    if(input < 10) {
        return input;
    }
    else {
        return (input % 10) * (int) Math.pow(10, (int) Math.log10(input)) + RevDigs(input/10);
        /* here we:
           - take last digit of input
           - multiply by an adequate power of ten
             (to set this digit in a "right place" of result)
           - add input without last digit, reversed
        */
    }
}
Run Code Online (Sandbox Code Playgroud)

input >= 0当然,这是假定的.