Edijs Malinovskis Edijs Malinovskis - 1 month ago 5
C++ Question

C++ code: not understood

Ok, I have C++ code, where programm need check if the entered number is a palindrome

code:

#include <iostream>
using namespace std;

int main()
{
int n, num, digit, rev = 0;

cout << "Enter a positive number: ";
cin >> num;

n = num;

do
{
digit = num % 10;
rev = (rev * 10) + digit;
num = num / 10;
} while (num != 0);

if (n == rev)
cout << " The number is a palindrome";
else
cout << " The number is not a palindrome";

return 0;
}


but I have a problem, I not understand this part:

do
{
digit = num % 10;
rev = (rev * 10) + digit;
num = num / 10;
}


someone would explain what is happening in these activities?

I do not understand how they calculated whether it is a palindrome.

Answer

Basically it calculates a number which is calculating by reversing each digit of the original number, if, in the end, both numbers are equal then number is palindrome.

You should try to test the code for a specific input, or add some print statements.

Start with num = 234

// iteration 1
digit = num % 10 = 234 % 10 = 4; // remainder of division
rev = (0 * 10) + 4 = 4;
num = num / 10 = 23; // integer division is truncated
// iteration 2
digit = num % 10 = 23 % 10 = 3;
rev = (4 * 10) + 3 = 43;
num = num / 10 = 2;
// iteration 3
digit = num % 10 = 2 % 10 = 2;
rev = (43 * 10) + 2 = 432; // you can see that 432 is the reverse of 234 in literal sense
num = num / 10 = 0;

so 432 != 234, hence it's not palindrome.