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

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

    & is the bitwise AND operator. && is the logical AND operator

    In binary, if the digits bit is set (i.e one), the number is odd.

    In binary, if the digits bit is zero , the number is even.

    (number & 1) is a bitwise AND test of the digits bit.

    Another way to do this (and possibly less efficient but more understandable) is using the modulus operator %:

    private static boolean isEven(int number)
    {
        if (number < 0)
           throw new ArgumentOutOfRangeException();
    
        return (number % 2) == 0;
    }
    
    0 讨论(0)
  • 2020-12-08 02:23

    This is Logical design concept bitwise & (AND)operater.

    return ( 2 & 1 ); means- convert the value to bitwise numbers and comapre the (AND) feature and returns the value.

    Prefer this link http://www.roseindia.net/java/master-java/java-bitwise-and.shtml

    0 讨论(0)
  • 2020-12-08 02:24

    Single & means bit-wise and operator not comparison

    So this code checks if the first bit (least significant/most right) is set or not, which indicates if the number is odd or not; because all odd numbers will end with 1 in the least significant bit e.g. xxxxxxx1

    0 讨论(0)
提交回复
热议问题