c++ - 如何在 C++ 中递归反转负整数?

标签 c++ recursion

我正在做一些递归练习,我需要编写一个程序来反转整数的输入

Example of input : cin >> 12345; The output should be 54321

但如果该整数为负数,则只需将负号附加到第一个数字。

Example of input : cin >> -1234; output -4321

我很难让我的程序适应负数。我运行时的设置方式

Example of test : 12345 I get the right output 54321

所以我的递归和基础是成功的。但如果我运行负数,我会得到

Example of test : -12345 I get this for a reason I don't understand -5-4-3-2 1

#include<iostream>
using namespace std;
void reverse(int);
int main()
{
    int num;
    cout << "Input a number : ";
    cin >> num;
    reverse(num);
    return 0;
}


void reverse(int in)
{
    bool negative = false;
    if (in < 0)
    {
        in = 0 - in;
        negative = true;
    }

    if (in / 10 == 0)
        cout <<  in % 10;
    else{
        if (negative == true)
            in = 0 - in;
        cout << in % 10;
        reverse(in / 10);
    }
}

最佳答案

要反转负数,您输出一个-,然后反转相应的正数。我建议使用递归而不是状态,如下所示:

void reverse(int in)
{
    if (in < 0)
    {
        cout << '-';
        reverse(-in);
    }
    else
    {
       // code to recursively reverse non-negative numbers here
    }
}

关于c++ - 如何在 C++ 中递归反转负整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36364955/

相关文章:

python - 递归 Python 函数削弱 Django 站点性能

c++ - 带构造函数和析构函数的链表问题

list - 递归地将列表的第一个元素附加到列表的其余部分

MYSQL CTE 递归更新

c++ 抽象类采用派生类参数

java - Java (JIT) 可以内联递归方法吗?

c++ - 返回不停止函数,递归函数问题? (编程练习,动态规划,Levenshtein Back-trace)

c++ - 调用基类构造函数的规则是什么?

c++ - 什么是 copy-and-swap 习语?

c++ - Python 等效于 vector::reserve()