What does this boolean “(number & 1) == 0” mean?

前端 未结 9 904
眼角桃花
眼角桃花 2020-12-08 01:27

On CodeReview I posted a working piece of code and asked for tips to improve it. One I got was to use a boolean method to check if an ArrayList had an even number of indices

9条回答
  •  独厮守ぢ
    2020-12-08 02:00

    Keep in mind that "&" is a bitwise operation. You are probably aware of this, but it's not totally clear to me based on the way you posed the question.

    That being said, the theoretical idea is that you have some int, which can be expressed in bits by some series of 1s and 0s. For example:

    ...10110110
    

    In binary, because it is base 2, whenever the bitwise version of the number ends in 0, it is even, and when it ends in 1 it is odd.

    Therefore, doing a bitwise & with 1 for the above is:

    ...10110110 & ...00000001
    

    Of course, this is 0, so you can say that the original input was even.

    Alternatively, consider an odd number. For example, add 1 to what we had above. Then

    ...10110111 & ...00000001
    

    Is equal to 1, and is therefore, not equal to zero. Voila.

提交回复
热议问题