Skip to content

Commit 0b95faa

Browse files
Add is_even_using_shift_operator function
Introduces a new function to check if a number is even using bitwise shift operators. Includes docstring with explanation and doctest examples.
1 parent 1562ae1 commit 0b95faa

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

bit_manipulation/is_even.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,40 @@ def is_even(number: int) -> bool:
3030
"""
3131
return number & 1 == 0
3232

33+
def is_even_using_shift_operator(number: int) -> bool:
34+
"""
35+
Returns True if the input integer is even.
36+
37+
Explanation:
38+
In binary, even numbers end with 0, odd numbers end with 1.
39+
Examples:
40+
2 -> 10
41+
3 -> 11
42+
4 -> 100
43+
5 -> 101
44+
45+
For odd numbers, the last bit is always 1.
46+
Using shift:
47+
(n >> 1) << 1 removes the last bit.
48+
If result equals n, n is even.
49+
50+
>>> is_even_using_shift_operator(1)
51+
False
52+
>>> is_even_using_shift_operator(4)
53+
True
54+
>>> is_even_using_shift_operator(9)
55+
False
56+
>>> is_even_using_shift_operator(15)
57+
False
58+
>>> is_even_using_shift_operator(40)
59+
True
60+
>>> is_even_using_shift_operator(100)
61+
True
62+
>>> is_even_using_shift_operator(101)
63+
False
64+
"""
65+
return (number >> 1) << 1 == number
66+
3367

3468
if __name__ == "__main__":
3569
import doctest

0 commit comments

Comments
 (0)