The Self-Taught Computer Scientist


Download 1.48 Mb.
Pdf ko'rish
bet60/147
Sana17.06.2023
Hajmi1.48 Mb.
#1540634
1   ...   56   57   58   59   60   61   62   63   ...   147
Bog'liq
books-library.net-11301817Az7X6

Chapter 6 Math
69
11 #3
1 #1
--
1
Because 1 has only one digit in binary, it doesn’t matter if the number you are checking for evenness 
has one binary digit or one thousand. Because 1 has only one binary digit, you make only one 
comparison: the last binary digit in the number and 1.
Here is how to check if a number is even or odd using the AND bitwise operator in Python:
def is_even(n):
return not n & 1
In your function 
is_even
, you return 
not n & 1
. Your code 
n & 1
uses the bitwise AND operator 
on 
n
and 
1
. Then, you use 
not
to change the result to the opposite of whatever it would have been, 
because when you perform bitwise AND on an even number and 1, it returns 
False
, which means the 
number is even. In this case, you want your function to return 
True
to represent that the number is 
even, so you use 
not
to switch 
True
to 
False
and 
False
to 
True
.
You can also use the bitwise AND operator to see if an integer is a power of 2. Every number that 
is a power of 2 has a single 1 in its binary representation because binary is base 2, which means any 
power of 2 has only a single 1. For example, the number 8 is 0b1000 in binary. Conversely, a number 
that is 1 less than a power of 2 contains all 1 bits. For example, the number 7, which is 1 less than 8, 
is 0b111 in binary.
When you apply the bitwise AND operator to these two binary numbers, you can see the resulting 
binary will be all zeros when the first number is a power of 2.
1000 # 8
0111 # 7 
— — — — 
0000
If the number is not a power of 2, there will be at least one binary digit that is a 1.
0111 # 7
0110 # 6
— — — — 
0001
Here is how to use the bitwise AND operator in Python to determine if a number is a power of 2:
def is_power(n):
if n & (n - 1) == 0:
return True
return False



Download 1.48 Mb.

Do'stlaringiz bilan baham:
1   ...   56   57   58   59   60   61   62   63   ...   147




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling