[Solved] Adding reversed numbers then reversing the sum


First, you need to rethink how to reverse a number.

Basically, what you want to do is to have a running total starting from 0.

Then starting from the rightmost digit in the number to reverse, you

1) Take the total and multiply it by 10. This “moves” the digits of the running total to the left by 1 place, leaving a 0 in the units place in the total.

2) Retrieve the rightmost digit from the input number you want to reverse, and add it to the total.

3) Divide the input number by 10 and store results back into the input number. If the result is 0, stop, else go to step 1).

That’s it.

So for example, to reverse the number 123:

1) Total = 0.

2) Total = (Total x 10) + (last_digit_of_number) = (0 x 10) + 3 = 3

3) Divide number by 10 (123 / 10), so number is now 12.

4) Total = (Total x 10) + (last_digit_of_number) = (3 x 10) + 2 = 32

5) Divide number by 10 (12 / 10), so number is now 1

6) Total = (Total x 10) + (last_digit_of_number) = (32 x 10) + 1 = 321

7) Divide number by 10 (1 / 10), so number is now 0. We can stop.

So Total is 321, thus the number has been reversed

Look at the code below:

unsigned long reverse_num(unsigned long num)
{
    unsigned long sum = 0;  // our running total
    while (num)    // keep going until our input is 0
    {
        sum = sum * 10 // multiply our running total by 10, so as to 
                       // shift it one place to the left
        +
                       // add on the following
        num % 10;      // to get the last digit of our input do a mod(10)

        num /= 10;     // divide by 10 to remove the last digit
    }
    return sum;  // return the result
}

So now the requirements are that you want to reverse the input of two reversed numbers. Simple:

unsigned long input1, input2;
cin >> input1 >> input2;
cout << reverse_num(reverse_num(input1) + reverse_num(input2));

The call is doing exactly what the assignment stated, literally. You are reversing the results of the sum of two reversed numbers.

2

solved Adding reversed numbers then reversing the sum