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

前端 未结 9 905
眼角桃花
眼角桃花 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:14

    & is a bitwise AND operation.

    For number = 8:

      1000
      0001
    & ----
      0000
    

    The result is that (8 & 1) == 0. This is the case for all even numbers, since they are multiples of 2 and the first binary digit from the right is always 0. 1 has a binary value of 1 with leading 0s, so when we AND it with an even number we're left with 0.

提交回复
热议问题