Skip to content

Commit 39a99b4

Browse files
Lauquikluciferx48cclaussgithub-actions
authored
check whether integer is even or odd using bit manupulation (TheAlgorithms#7099)
* even_or_not file added * Updated DIRECTORY.md * modified DIRECTORY.md * Update bit_manipulation/even_or_not.py * updating DIRECTORY.md * Rename even_or_not.py to is_even.py * updating DIRECTORY.md Co-authored-by: luciferx48 <laukik.22010776@gmail.com> Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent b8b6346 commit 39a99b4

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
* [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py)
4646
* [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py)
4747
* [Gray Code Sequence](bit_manipulation/gray_code_sequence.py)
48+
* [Is Even](bit_manipulation/is_even.py)
4849
* [Reverse Bits](bit_manipulation/reverse_bits.py)
4950
* [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py)
5051

bit_manipulation/is_even.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
def is_even(number: int) -> bool:
2+
"""
3+
return true if the input integer is even
4+
Explanation: Lets take a look at the following deicmal to binary conversions
5+
2 => 10
6+
14 => 1110
7+
100 => 1100100
8+
3 => 11
9+
13 => 1101
10+
101 => 1100101
11+
from the above examples we can observe that
12+
for all the odd integers there is always 1 set bit at the end
13+
also, 1 in binary can be represented as 001, 00001, or 0000001
14+
so for any odd integer n => n&1 is always equlas 1 else the integer is even
15+
16+
>>> is_even(1)
17+
False
18+
>>> is_even(4)
19+
True
20+
>>> is_even(9)
21+
False
22+
>>> is_even(15)
23+
False
24+
>>> is_even(40)
25+
True
26+
>>> is_even(100)
27+
True
28+
>>> is_even(101)
29+
False
30+
"""
31+
return number & 1 == 0
32+
33+
34+
if __name__ == "__main__":
35+
import doctest
36+
37+
doctest.testmod()

0 commit comments

Comments
 (0)