Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
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.
  • Loading branch information
ArunKishoreVoleti committed Oct 14, 2025
commit 0b95faaafaf94a1ab176b6bfc67b1243035a32bf
34 changes: 34 additions & 0 deletions bit_manipulation/is_even.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,40 @@ def is_even(number: int) -> bool:
"""
return number & 1 == 0

def is_even_using_shift_operator(number: int) -> bool:
"""
Returns True if the input integer is even.

Explanation:
In binary, even numbers end with 0, odd numbers end with 1.
Examples:
2 -> 10
3 -> 11
4 -> 100
5 -> 101

For odd numbers, the last bit is always 1.
Using shift:
(n >> 1) << 1 removes the last bit.
If result equals n, n is even.

>>> is_even_using_shift_operator(1)
False
>>> is_even_using_shift_operator(4)
True
>>> is_even_using_shift_operator(9)
False
>>> is_even_using_shift_operator(15)
False
>>> is_even_using_shift_operator(40)
True
>>> is_even_using_shift_operator(100)
True
>>> is_even_using_shift_operator(101)
False
"""
return (number >> 1) << 1 == number


if __name__ == "__main__":
import doctest
Expand Down