Check if number is multiple of 5 in most efficient way

Solution 1:

  1. The most straightforward way to check if a number is a multiple of 5 is to simply
if (n % 5 == 0) {
    // logic...
}

What the bit manipulation code does is:

  1. If the number is odd, multiply it by two. Notice that for multiples of 5, the ones digit will end in either 0 or 5, and doubling the number will make it end in 0.
  2. We create a number x that is set to n, but with a ones digit set to 0. (We do this by multiplying n by 0.1, which removes the ones digit, and then multiply by 10 in order to add a 0, which has a total effect of just changing the ones digit to 0).
  3. We know that originally, if n was a multiple of 5, it would have a ones digit of 0 after step 1. So we check if x is equal to it, and if so, then we can say n was a multiple of 5.