简体   繁体   中英

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

I'm tasked with writing a program that outputs the binary representation of a decimal integer. It uses the decimal 13 for example, where the desired output is 1101.

My problem is, my neither of the functions in my program print this number in the correct order. They both print it backwards from the desired order.

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 ,最后您将反转它。

You could store it in a string and output the reverse:

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

Or, you could do this for the recursive function (if you don't care too much about the endl ):

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

    cout << remainder;
}

Here's a working example

I believe this should do the trick:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM