我正在做一些递归练习,我需要编写一个程序来反转整数的输入
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
所以我的递归和基础是成功的。但如果我运行负数,我会得到 p>
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/