[Tutor] Finding even and odd numbers
Ewald Ertl
ewald.ertl at gmail.com
Wed Sep 19 15:06:55 CEST 2007
Hi Boyks,
Boykie Mackay wrote:
> Hi guys,
>
> I have come across a bit of code to find if a group of numbers is odd or
> even.The code snippet is shown below:
>
> if not n&1:
> return false
>
> The above should return false for all even numbers,numbers being
> represented by n.I have tried to wrap my head around the 'not n&1' but
> I'm failing to understand what's going on.Could someone please explain
the single '&' is a bitwise and operator.
every odd number has the first bit set so <odd number>&1 returns 1.
The binray representation of :
1 0001
2 0010
3 0011
4 0100
>>> 1&1
1
>>> 2&1
0
>>> 3&1
1
>>> 4&1
0
HTH Ewald
More information about the Tutor
mailing list