-1

I am writing code in c++ to detect if an input number is a Palindrome Number, which means its reverse is the same as the origin. I have problems computing the reverse int.

e.g.

121 returns true;
123 returns false;
12321 returns true;
10 returns false;

I input 123 and the sum should be 321. However, my code keeps returning 386. I stepped into the function with xcode. Still, I have no idea why reverse += (3 * 10) + 2 turns to be 35 or why the final reverse number to be 386.

int origin = x;
int reverse = 0;

while (x != 0) {
    int digit = x % 10;
    reverse += ((reverse * 10) + digit);
    x /= 10;
}
Erin
  • 83
  • 1
  • 9

1 Answers1

0

why reverse += (3 * 10) + 2 turns to be 35

Because += adds what is on the right to the existing value of what’s on the left. (3 * 10) + 2 is 32, but reverse was already 3 and so you are adding your 32 to the existing 3, which is 35.

You don’t want to add to the value of reverse; you want to replace it.

Change

reverse += ((reverse * 10) + digit)

To

reverse = ((reverse * 10) + digit)
matt
  • 515,959
  • 87
  • 875
  • 1,141