如何在C++中反转输出顺序?(有或没有递归)

How do I reverse the order of output in C++? ( With or without recursion)

本文关键字:递归 顺序 输出 C++      更新时间:2023-10-16

我的任务是编写一个程序,输出十进制整数的二进制表示。例如,它使用十进制13,其中所需的输出为1101。

我的问题是,我的程序中的两个函数都没有按正确的顺序打印这个数字。他们都按所需顺序倒排打印。

int binaryRecursion(int decimalInteger) //This function uses recursion
{
    int remainder = decimalInteger % 2;
    cout << remainder;
    if ( decimalInteger / 2 == 0 )
    {
        cout << endl;
    }else{
        return binaryRecursion(decimalInteger / 2);
    }
    return 1;
}
void binaryNormal(int decimalInteger) //This function does NOT use recursion
{
    while (decimalInteger != 0)
    {
        int remainder = decimalInteger % 2;
        cout << remainder;
        decimalInteger /= 2;
    }
}
int main()
{
    int decimalInteger;
    cout << "Enter your decimal integer." << endl;
    cin >> decimalInteger;
    binaryRecursion(decimalInteger);
    binaryNormal(decimalInteger);
    return 0;
}

不要直接输出它,而是将它放在一个不断增长的std::string中,最终将其反转。

我相信这应该能奏效:

void binaryRecursion(int decimalInteger) //This function uses recursion
{
    int remainder = decimalInteger % 2;
    if ( decimalInteger / 2 != 0 )
    {
        binaryRecursion(decimalInteger / 2);
    }
    cout << remainder;
}

您可以将其存储在string中并输出相反的结果:

void binaryNormal(int decimalInteger) //This function does NOT use recursion
{
    string buff = "";
    while (decimalInteger != 0)
    {
        int remainder = decimalInteger % 2;
        buff += remainder + '0';
        decimalInteger /= 2;
    }
    for(int i = buff.length() - 1; i >= 0; cout << buff[i--]);
    cout << endl;
}

或者,您可以对递归函数执行此操作(如果您不太关心endl):

void binaryRecursion(int decimalInteger) //This function uses recursion
{
    int remainder = decimalInteger % 2;
    if (decimalInteger / 2 > 0) binaryRecursion(decimalInteger / 2);
    cout << remainder;
}

下面是一个工作示例