Understanding code

Hello everyone! I am doing some exercises and when i can't solve them i come to google and try to solve and understand them but i have a problem here understanding how to reverse an int. Here's the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  bool esPal(int z)
{
	int t = z;
	int rev = 0;

	
	while (z > 0) {
		int dig = z % 10; 
		rev = rev * 10 + dig; //Don't understand how these operations reverse the number
		z = z / 10;

	

	}

Could someone explain me line by line the while loop that reverses the int? I do not get how doing the module of z and then multiplying by ten and adding can invert/reverse the string.

Thank you very much!
Delsh
int dig = z % 10;
z % 10 calculates number modulo 10. If we write our number in decimal, it have same effect as read last digit.
rev = rev * 10 + dig;
Here we:
1) Multiply number by 10 (eqivalent to writng 0 at the end)
2) add digit we get from previous line. As last digit is 0 (by 1), both steps are equivalet to "write digit at the end"
z = z / 10;
Integer division eqivalent to "remove last digit"

So whole algorithm is:
1) Take the last digit of original number
2) Append it to the end of reversed number
3) Erase last digit of original
repeat.
When you're doing stuff like this it's best you write it on a piece of paper so you can then understand how they got there. For example, let say Z is 15. 15 % 10 is 5.0. 0 * 10 + 5.0 = 5.0. 15 / 10 is 1.5. The loop continues. 1.5 /10 is 1.0. 5 * 10 + 1.5 is 51.5 or 51 because the integers gets truncated. So, the opposite of 15 is 51. If you want to, use any other number, work out the steps on a piece of paper, and you should then see the process unfold before your very eyes.
Last edited on
Thank you very much guys! Much clearer now!
Topic archived. No new replies allowed.