This is a bitwise ‘and’ operation (be prepared for some binary).
Using the bitwise &
operation is similar to using a regular ‘and’ in Python.
For example, using the ‘and’, if you have:
True and True, you get True as the result.
True and False, you get False as the result.
False and True, you get False as the result.
False and False, you get False as the result.
So, say I have a number n = 10 and k = 5.
In binary, we can say n = 1010, and k = 0101.
Now, what the bitwise &
will do is compare each integer from the binary in the same sequence, exactly like what the regular ‘and’ would do.
So, if we compare n (10) and k (5), we compare:
1010
0101
Looking at the first digit, we see they’re not both 1’s.
So, our first digit is zero. This occurs for all of our digits, meaning our result is 0.
Another example could be n = 13, and k = 11.
In binary, these numbers are 1101 and 1011, respectively. So, we compare:
1101
1011
Our first digit matches (both 1’s), so it gives us a 1 for the first digit. Our second digits place and our third digits place don’t match this, but our fourth does.
So, we get:
1001 as our final result (in binary), which is equal to 9.
So, we can use this knowledge to check what (n & 1 == 1) does.
It uses the bitwise &
operation with some number ’n’ and 1.
Now, keep in mind that 1 in binary is just represented by multiple zeroes (31 zeroes actually), then a 1,
like this: 000…0001
Meanwhile, n could be something
like this: 11101…….1
or like this: 1001……0
or any number of combinations ending in 0 or 1.
Now, because 1 in binary is simply represented as a bunch of zeroes, then we really only need to think about the last digits place, because if we have a 0 in every other space for our first number when comparing, we must always get zeroes when using our bitwise &.
So, when we consider (n & 1 == 1), we realize that this can only return true if the last digit of n is 1, because we already know that the last digit of 1 is definitely 1, while all others are 0. This means our only possible result for n & 1 is either 0 or 1, depending on if the last digit of n is a 1, because all other digits will have to be 0 in our result.
And when will the last digit of n be 1? Whenever n is odd (keep in mind how binary works - if you don’t understand this, I recommend you look it up). So, we return true whenever n is an odd number.
Thus, this is a method to check whether or not n is an odd number. It will return true if n is odd, and it will return false if n is even.