-2

Found some code online I was looking at to solve a problem, and I'm not exactly sure what it's doing where it says "(candidate & 1) == 0". candidate is an int.

 if ((candidate & 1) == 0)
            {
                if (candidate == 2)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
son rohan
  • 92
  • 1
  • 8

1 Answers1

2

It's the binary (bitwise) AND operator. In your case the if statement is checking whether the least significant bit is 1, or in other words, whether candidate is even:

Example using numbers 35 and 34:

35 & 1 = 0b100011 & 0b1 == 1 => odd
34 & 1 = 0b100010 & 0b1 == 0 => even

See also: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/and-operator

adjan
  • 13,371
  • 2
  • 31
  • 48