简体   繁体   English

有人可以向我解释此代码的工作原理吗? (回文C ++)

[英]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 . 通过遍历num的数字来反转num For each digit it adds it to the right of rev . 对于每个数字,它将其添加到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 : 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 . 321的确相反于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. 如果输入1234,则循环前的num是1234,而rev是0。

First line gets you 4 of 1234 (modulo, the remainder of a division). 第一行让您得到1234的4(取模,除法的余数)。

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). 您将num除以10,通常为123.4,但这是一个int ,因此只有123。这两行实际上删除了num的最后一位(并将其存储在位数中)。

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 如果rev为123, digit为4,则得到123*10+4=1234

So, remembering the loop: Digits are taken from the end of num and put at the end of rev instead. 因此,请记住循环:数字从num的末尾取而代之以rev的末尾。 Until there is no num anymore. 直到没有num为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM