0
0
DSA Pythonprogramming~10 mins

Check if Number is Even or Odd Using Bits in DSA Python - Execution Trace

Choose your learning style9 modes available
Concept Flow - Check if Number is Even or Odd Using Bits
Start with number n
Extract least significant bit (n & 1)
Is bit 0?
YesNumber is Even
No
Number is Odd
We check the last bit of the number using bitwise AND with 1. If it is 0, the number is even; if 1, it is odd.
Execution Sample
DSA Python
n = 5
if (n & 1) == 0:
    print("Even")
else:
    print("Odd")
This code checks the last bit of 5 to decide if it is even or odd.
Execution Table
StepOperationValue of nBitwise n & 1Condition (n & 1 == 0)ResultOutput
1Start5
2Calculate n & 151
3Check if n & 1 == 051FalseOddOdd
4End51FalseOddOdd
💡 Condition n & 1 == 0 is False, so number is Odd and output is printed.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
n5555
n & 1111
Condition (n & 1 == 0)FalseFalse
OutputOddOdd
Key Moments - 3 Insights
Why do we use 'n & 1' to check even or odd?
Because the least significant bit (rightmost bit) of a binary number tells if it is even (0) or odd (1). See execution_table step 2 where n & 1 extracts this bit.
Why does 'n & 1 == 0' mean the number is even?
If the last bit is 0, the number is divisible by 2, so it is even. This is shown in execution_table step 3 where the condition is checked.
What happens if the number is 0?
0 & 1 equals 0, so the condition is True and the number is even. This is consistent with the logic in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'n & 1' at step 2 for n=5?
A1
B0
C5
DUndefined
💡 Hint
Check the 'Bitwise n & 1' column at step 2 in execution_table.
At which step does the condition 'n & 1 == 0' evaluate to False?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Condition (n & 1 == 0)' column in execution_table.
If n was 4 instead of 5, what would be the output according to the execution_table logic?
AOdd
BError
CEven
DNo output
💡 Hint
Recall that even numbers have last bit 0, so n & 1 == 0 would be True.
Concept Snapshot
Check even or odd using bits:
Use 'n & 1' to get last bit.
If last bit is 0, number is even.
If last bit is 1, number is odd.
Fast and efficient bitwise check.
Full Transcript
This concept shows how to check if a number is even or odd using bitwise operations. We use the bitwise AND operator '&' with 1 to extract the least significant bit of the number. If this bit is 0, the number is even; if it is 1, the number is odd. The execution table traces the steps for n=5, showing the calculation of n & 1, the condition check, and the final output. The variable tracker shows how variables change during execution. Key moments clarify why the last bit determines even or odd and what happens with zero. The visual quiz tests understanding of these steps. This method is a quick and efficient way to check parity without division or modulus.