Check if Number is Even or Odd Using Bits in DSA Python - Time & Space Complexity
We want to know how fast we can tell if a number is even or odd using bits.
How does the time to check change as the number gets bigger?
Analyze the time complexity of the following code snippet.
def is_even(num: int) -> bool:
return (num & 1) == 0
number = 42
print(is_even(number)) # True if even, False if odd
This code uses a bitwise AND to check the last bit of the number to decide if it is even or odd.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single bitwise AND operation.
- How many times: Exactly once per function call.
The operation always takes the same time no matter how big the number is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time does not grow with input size; it stays constant.
Time Complexity: O(1)
This means the check takes the same small amount of time no matter how big the number is.
[X] Wrong: "Checking bits takes longer for bigger numbers because they have more bits."
[OK] Correct: The operation only looks at the last bit, so it always takes the same time regardless of number size.
Knowing this quick bit check shows you understand how computers work with numbers and can write very fast code.
"What if we checked multiple bits to find if a number is divisible by 4? How would the time complexity change?"