Can someone explain how reversing an integer using % 10 works?

105 Views Asked by At

To reverse an integer and put it into a list, one would do the following (where x is some integer):

    int lastDigit = x;
    while(lastDigit != 0)
    {
        list.add(lastDigit % 10);
        lastDigit /= 10;
    }

So if x was 502, 2 0 and 5 would get added to the list.

This is obviously really useful, but until yesterday I thought the only way to do something like this was by converting the int to a string first.

I'm not sure if this is just common knowledge but I had not seen this method before today. I would like to understand how it works instead of merely memorizing it.

Could someone explain why the number modulus 10 gives the last digit, and why dividing it by 10 gives the next digit on the next iteration? Why would it eventually equal 0?

2

There are 2 best solutions below

0
On

The modulus operator gives you the remainder from doing a division calculation.

502 % 10 is 2 because 502/10 = 50 plus a remainder of 2. Therefore the remainder in this calculation is 2, meaning 2 will be added to the list.

The division by ten in the next line is performed using integer arithmetic, so 502/10 gives a result of 50.

Any non-negative number less than 10 will give a result of zero, ending the loop.

0
On

Think of % 10 as getting the least significant (right most) digit in decimal system (hence 10).

And then think of / 10 as shifting all digits one place right (also decimal). You obviously have to do it until the number is 0. All remaining digits can be understood as leading zeros in this case.

In binary system you can also use the bitwise operations & 1 and >> 1 instead of modulo (% 2) and integer (/ 2) divisions.

The list append operation (here add) is the one that reverses the order. The operations above are just for extraction of the single digits.