使用递归来反转整数而不使用字符串 [英] Using Recursion to reverse an integer without the use of strings

查看:129
本文介绍了使用递归来反转整数而不使用字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying this for some time now but could not get it to work. I am trying to have a method to reverse an integer without the use of strings or arrays. For example, 123 should reverse to 321 in integer form.

我的第一次尝试:

/** 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;
}//======================

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

I also tried to use this, but it seems to mess up middle digits:

/** 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;
}

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

I have tried looking at some examples on the site, however I could not get them to work properly. To further clarify, I cannot use a String, or array for this project, and must use recursion. Could someone please help me to fix the problem. Thank you.

推荐答案

怎么样:

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
        */
    }
}

这假设输入> = 0 ,当然。

这篇关于使用递归来反转整数而不使用字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆