-3

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?

Ryan Williams
  • 119
  • 2
  • 8
  • 1
    Do it by hand for a few numbers. It should be quite instructive! – Hermann Döppes Jan 04 '17 at 22:08
  • 2
    This is just basic arithmetic. The modulus operator gives you the remainder that would be obtained in a division calculation, so 502 % 10 is 2 because 502/10 = 50 plus a remainder of 2. The division by ten in the next line is performed using integer arithmetic, so 502/10 gives a result of 50. And any non-negative number less than 10 will give a result of zero, ending the loop – r3mainer Jan 04 '17 at 22:09
  • You should read about the `mod` function and its usage. If you take `mod` of a number with `10` it gives back the unit digit as the remainder. Here, you are basically chopping off the unit digits by taking `mod` and then dividing the number by `10`. – user2004685 Jan 04 '17 at 22:10
  • This kind of algorithm is commonly used for problems which require processing each digit of a number. I think it just so happens that you haven't looked up solutions for that kind of problem before. – 4castle Jan 04 '17 at 22:15

2 Answers2

0

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

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.

Martin Sugioarto
  • 340
  • 3
  • 15