简体   繁体   中英

Can someone explain me how this code works? (Palindrome C++)

I have a working code but I don't quite understand how it works, I know it's meaning and use but I don't understand how it works.

#include <iostream> 
#include <string> 
using namespace std; 
int main(int argc, char* argv[]) 
{ 
   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);
     cout << " The reverse of the number is: " << rev << endl;
     if (n==rev)
       cout << " The number is a palindrome";
     else
       cout << " The number is not a palindrome";

    return 0;  
} 

I don't understand this part:

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

This reverses num by iterating over the digits of num . For each digit it adds it to the right of rev .

digit = num%10; // Find the 1s digit of num
rev = (rev*10) + digit; // Push digit to the right of rev
num = num/10; // Remove the 1s digit of num

An example walkthrough for num = 123 :

d = 0, r = 0, n = 123.

d = 3   // 123%10
r = 3   // 0*10 + 3
n = 12  // 123/10

d = 2   // 12%10
r = 32  // 3*10+2
n = 1   // 12/10

d = 1   // 1%10
r = 321 // 32*10+1
n = 0   // 1/10

And 321 is indeed the reverse of 123 .

Let´s reorder it a bit and forget the loop for now.

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

If you enter 1234, num is 1234 before the loop, and rev is 0.

First line gets you 4 of 1234 (modulo, the remainder of a division).

The you divide num by 10, which normally would be 123.4, but it´s an int , so only 123. These two lines essentially remove the last digit of num (and store it in digit).

The, the last line simply "concatenates" the digit to rev.
If rev is 123 and digit is 4, you´ll get 123*10+4=1234

So, remembering the loop: Digits are taken from the end of num and put at the end of rev instead. Until there is no num anymore.

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