Search code examples
c++reversepalindrome

Understanding int reversing logic


I'm new to C++.
So I found this reverse code on the internet. My prof. told me to make a palindrome checker, so I look for the reverse first.
Here is what I made

void main() 
{
    int num;
    int new_num = 0;
    int dummy;

    cout << "Masukkan angka";
    cin >> num;

    dummy = num;
    cout << dummy << endl;

    while (num > 0)
    {
        new_num = new_num*10 + (num % 10);
        num = num/10;
    }
    cout << new_num << endl;

    if ( new_num == dummy)
    {
        cout << "true";
    }
    else 
        cout<<"false";

    getch();
}

The most confusing part is this

while(num > 0)
{
    new_num = new_num*10 + (num % 10);
    num = num/10;
}
cout << new_num << endl;

I found this on the internet and I don't know how it works. Can someone explain how this code can reverse the number I input? Like when I input 12345, the output would be 54321. I can't understand.


Solution

  • Its talking the last char of your input by using modulo.

    input is: 12345

    Cycle 1:

    1. new_num is 0, multiply by 10 give 0.
    2. add modulo or your input 12345 % 10 = 5, new_num is now 5.
    3. divide your input by 10 to remove last digit. input = 1234

    Cycle 2,3,4 etc.:

    1. new_num is 5, multiply by 10 gives 50.
    2. add modulo or your input 1234 % 10 = 4, new_num is now 54.
    3. divide your input by 10 to remove last digit. input = 123