Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Check if Number is Even or Odd Using Bits in DSA Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Check if Number is Even or Odd Using Bits
What is it?
Checking if a number is even or odd using bits means looking at the number's binary form and using a simple operation to decide if it divides evenly by two. Instead of dividing the number, we use a bitwise operation that is very fast and efficient. This method uses the fact that even numbers always end with a 0 in binary, and odd numbers end with a 1. It is a quick way to tell if a number is even or odd without doing slow math.
Why it matters
This method exists because computers work with bits, the smallest pieces of data, and bitwise operations are very fast. Without this, checking even or odd would rely on division or modulus operations, which are slower. In real life, this means programs can run faster and use less power, especially when checking many numbers quickly, like in games or data processing.
Where it fits
Before learning this, you should understand what binary numbers are and how numbers are stored in computers. After this, you can learn about other bitwise operations and how they help in optimizing algorithms or working with low-level data.
Mental Model
Core Idea
The last bit of a number's binary form tells if it is even (0) or odd (1).
Think of it like...
It's like checking if a light switch is off or on; if the switch is off (0), the number is even, and if it's on (1), the number is odd.
Number in binary: ... b3 b2 b1 b0
Check last bit (b0):
  0 -> Even number
  1 -> Odd number

Example:
  6 in binary: 110 (last bit 0) -> Even
  7 in binary: 111 (last bit 1) -> Odd
Build-Up - 6 Steps
1
FoundationUnderstanding Binary Numbers
🤔
Concept: Learn how numbers are represented in binary form using bits.
Every number in a computer is stored as a sequence of bits (0s and 1s). Each bit represents a power of two. For example, the number 5 is 101 in binary because it is 1*4 + 0*2 + 1*1. The rightmost bit is the smallest value (1s place).
Result
You can convert any decimal number to binary and see its bits clearly.
Understanding binary is essential because bitwise operations work directly on these bits.
2
FoundationWhat Makes a Number Even or Odd
🤔
Concept: Even numbers end with 0 in binary, odd numbers end with 1.
In decimal, even numbers are divisible by 2 without remainder. In binary, this means the last bit is 0. Odd numbers have a last bit of 1. For example, 4 (100) ends with 0, so it's even; 5 (101) ends with 1, so it's odd.
Result
You can tell if a number is even or odd just by looking at its last bit.
This simple property allows us to check even or odd without division.
3
IntermediateUsing Bitwise AND to Check Last Bit
🤔Before reading on: do you think using AND with 1 will keep or remove the last bit? Commit to your answer.
Concept: Bitwise AND with 1 isolates the last bit of a number.
The bitwise AND operation compares each bit of two numbers and returns 1 only if both bits are 1. When you AND any number with 1 (binary 0001), all bits except the last become 0. So, number & 1 gives 0 if last bit is 0 (even), or 1 if last bit is 1 (odd). Example: 6 & 1 = 110 & 001 = 000 (0) -> even 7 & 1 = 111 & 001 = 001 (1) -> odd
Result
You get 0 for even numbers and 1 for odd numbers.
Knowing that AND with 1 extracts the last bit is the key to this fast check.
4
IntermediateImplementing Even/Odd Check in TypeScript
🤔Before reading on: do you think the function returns true for even or odd numbers? Commit to your answer.
Concept: Write a simple function using bitwise AND to check even or odd.
function isEven(num: number): boolean { return (num & 1) === 0; } This function returns true if the last bit is 0 (even), false otherwise (odd). Example calls: console.log(isEven(4)); // true console.log(isEven(7)); // false
Result
The function correctly identifies even and odd numbers quickly.
Implementing this in code shows how theory translates to practice.
5
AdvancedWhy Bitwise is Faster Than Modulus
🤔Before reading on: do you think bitwise operations are slower, faster, or the same speed as modulus? Commit to your answer.
Concept: Bitwise operations are simpler and faster at the machine level than division or modulus.
Modulus (%) requires division, which is a complex and slower operation for the CPU. Bitwise AND is a single CPU instruction that directly manipulates bits. This makes bitwise checks faster, especially in loops or performance-critical code. Benchmarking shows bitwise is often several times faster than modulus for even/odd checks.
Result
Using bitwise operations improves performance in programs that check many numbers.
Understanding CPU-level efficiency helps write faster, more efficient code.
6
ExpertHandling Negative Numbers and Edge Cases
🤔Before reading on: do you think the bitwise even/odd check works the same for negative numbers? Commit to your answer.
Concept: Bitwise operations work on two's complement binary, so negative numbers behave consistently for even/odd checks.
In two's complement, the last bit still indicates even or odd. For example, -3 in binary ends with 1, so it's odd. The bitwise AND with 1 works the same for negative numbers. Example: console.log(isEven(-4)); // true console.log(isEven(-3)); // false However, beware of non-integer inputs or very large numbers where bitwise operations may behave unexpectedly due to JavaScript's 32-bit bitwise limit.
Result
The bitwise method reliably checks even/odd for negative integers but watch for non-integers.
Knowing how two's complement works prevents bugs when using bitwise checks on negative numbers.
Under the Hood
Bitwise AND compares each bit of two numbers. When ANDed with 1 (binary 0001), all bits except the least significant bit become zero. The CPU executes this as a single, fast instruction. Numbers in computers use two's complement for negatives, but the last bit still shows parity. This avoids division, which requires multiple CPU cycles.
Why designed this way?
Computers use binary because it is reliable and simple to implement with electrical circuits. Bitwise operations are designed to manipulate bits directly for speed and efficiency. Checking even or odd by looking at the last bit is a natural consequence of binary representation and was adopted because it is faster than arithmetic operations.
Number (binary):  ... b3 b2 b1 b0
                     │  │  │  │
                     │  │  │  └─ Last bit (b0)
                     │  │  └──── Other bits
                     │  └───────
                     └─────────

Operation: num & 1
  Only last bit remains:
  If b0 = 0 -> result 0 (even)
  If b0 = 1 -> result 1 (odd)
Myth Busters - 3 Common Misconceptions
Quick: Does bitwise even/odd check fail for negative numbers? Commit yes or no.
Common Belief:Bitwise even/odd check does not work correctly for negative numbers.
Tap to reveal reality
Reality:Bitwise AND with 1 works correctly for negative numbers in two's complement representation.
Why it matters:Believing this may cause unnecessary complex code or avoiding efficient bitwise checks.
Quick: Is bitwise AND with 1 the same as modulus 2? Commit yes or no.
Common Belief:Bitwise AND with 1 and modulus 2 are completely different and give different results.
Tap to reveal reality
Reality:Both give the same result for integers, isolating the last bit to check even or odd.
Why it matters:Understanding this equivalence helps choose faster operations without changing logic.
Quick: Can bitwise operations be used on decimal fractions to check even/odd? Commit yes or no.
Common Belief:Bitwise operations work on any number, including decimals, to check even or odd.
Tap to reveal reality
Reality:Bitwise operations only work on integers; decimals are converted to integers or cause unexpected results.
Why it matters:Using bitwise on decimals can cause bugs or wrong results.
Expert Zone
1
Bitwise operations in JavaScript work on 32-bit signed integers, so very large numbers lose precision in bitwise checks.
2
Negative numbers use two's complement, so the last bit still indicates parity, but understanding this avoids confusion.
3
Using bitwise checks in tight loops or performance-critical code can significantly reduce CPU usage compared to modulus.
When NOT to use
Avoid bitwise even/odd checks when working with non-integer numbers, very large integers beyond 32-bit range, or when code clarity is more important than micro-optimizations. Use modulus (%) for clarity in general-purpose code.
Production Patterns
In performance-sensitive applications like game engines, graphics, or embedded systems, bitwise even/odd checks are common. They appear in algorithms that filter or branch based on parity without costly division. Also used in low-level device drivers and systems programming.
Connections
Two's Complement Representation
Builds-on
Understanding two's complement explains why bitwise parity checks work the same for negative numbers.
CPU Instruction Set Architecture
Builds-on
Knowing how CPUs execute bitwise instructions helps appreciate why bitwise operations are faster than arithmetic.
Digital Logic Circuits
Builds-on
Bitwise operations mirror how logic gates work in hardware, connecting software operations to physical electronics.
Common Pitfalls
#1Using bitwise AND on decimal numbers expecting correct even/odd check.
Wrong approach:function isEven(num: number): boolean { return (num & 1) === 0; } console.log(isEven(4.2)); // Unexpected result
Correct approach:function isEven(num: number): boolean { if (!Number.isInteger(num)) throw new Error('Input must be an integer'); return (num & 1) === 0; } console.log(isEven(4)); // true
Root cause:Bitwise operations convert numbers to 32-bit integers, so decimals lose fractional parts causing wrong results.
#2Assuming bitwise even/odd check works for very large numbers beyond 32-bit integer range.
Wrong approach:const bigNum = 9007199254740993; // Larger than 2^53 console.log((bigNum & 1) === 0); // Incorrect due to precision loss
Correct approach:const bigNum = 9007199254740993; console.log((bigNum % 2) === 0); // Correct for large numbers
Root cause:JavaScript bitwise operators work on 32-bit signed integers, causing precision loss for large numbers.
#3Using bitwise check without understanding two's complement for negative numbers and doubting results.
Wrong approach:console.log((-3 & 1) === 0); // false, but misunderstood
Correct approach:console.log((-3 & 1) === 1); // true, odd number
Root cause:Lack of understanding of two's complement representation leads to confusion about negative number parity.
Key Takeaways
The last bit of a binary number determines if it is even or odd: 0 means even, 1 means odd.
Bitwise AND with 1 is a fast way to check the last bit and thus the parity of a number.
This method is faster than using modulus because bitwise operations are simpler CPU instructions.
Bitwise parity checks work correctly for negative integers due to two's complement representation.
Be cautious using bitwise operations on decimals or very large numbers due to language and hardware limits.

Practice

(1/5)
1. What does the expression num & 1 check when determining if a number is even or odd?
easy
A. It checks if num is greater than 1.
B. It checks if the least significant bit of num is 1, indicating odd number.
C. It checks if num is divisible by 2 without remainder.
D. It checks if num is negative.

Solution

  1. Step 1: Understand bitwise AND with 1

    The expression num & 1 isolates the least significant bit (rightmost bit) of the number.
  2. Step 2: Interpret the least significant bit

    If the least significant bit is 1, the number is odd; if 0, it is even.
  3. Final Answer:

    It checks if the least significant bit of num is 1, indicating odd number. -> Option B
  4. Quick Check:

    num & 1 = 1 means odd [OK]
Hint: Check last bit with & 1; 1 means odd, 0 means even [OK]
Common Mistakes:
  • Thinking & 1 checks divisibility by 2
  • Confusing bitwise AND with logical AND
  • Assuming it checks if number is negative
2. Which of the following TypeScript code snippets correctly checks if a number n is even using bitwise operators?
easy
A. if ((n & 1) === 0) { console.log('Even'); } else { console.log('Odd'); }
B. if ((n | 1) === 0) { console.log('Even'); } else { console.log('Odd'); }
C. if ((n & 0) === 1) { console.log('Even'); } else { console.log('Odd'); }
D. if ((n ^ 1) === 0) { console.log('Even'); } else { console.log('Odd'); }

Solution

  1. Step 1: Understand bitwise AND with 1

    The expression n & 1 extracts the least significant bit of n.
  2. Step 2: Check if least significant bit is zero

    If (n & 1) === 0, the number is even; otherwise, it is odd.
  3. Final Answer:

    if ((n & 1) === 0) { console.log('Even'); } else { console.log('Odd'); } -> Option A
  4. Quick Check:

    Use n & 1 === 0 for even check [OK]
Hint: Use (n & 1) === 0 to check even numbers [OK]
Common Mistakes:
  • Using bitwise OR instead of AND
  • Comparing with wrong values like 0 or 1 incorrectly
  • Using XOR without understanding its effect
3. What will be the output of the following TypeScript code?
const numbers = [2, 3, 4, 5];
numbers.forEach(num => {
  if (num & 1) {
    console.log(num + ' is Odd');
  } else {
    console.log(num + ' is Even');
  }
});
medium
A. 2 is Odd 3 is Odd 4 is Odd 5 is Odd
B. 2 is Even 3 is Even 4 is Even 5 is Even
C. 2 is Odd 3 is Even 4 is Odd 5 is Even
D. 2 is Even 3 is Odd 4 is Even 5 is Odd

Solution

  1. Step 1: Evaluate bitwise AND for each number

    For each number, num & 1 checks the last bit: 2 & 1 = 0 (even), 3 & 1 = 1 (odd), 4 & 1 = 0 (even), 5 & 1 = 1 (odd).
  2. Step 2: Print corresponding output

    Numbers with num & 1 === 1 print 'Odd', others print 'Even'.
  3. Final Answer:

    2 is Even 3 is Odd 4 is Even 5 is Odd -> Option D
  4. Quick Check:

    Bitwise check matches even/odd output [OK]
Hint: Check each number's last bit; 1 means odd, 0 means even [OK]
Common Mistakes:
  • Assuming all numbers are odd
  • Confusing bitwise AND with logical AND
  • Printing wrong labels for even/odd
4. Identify the error in this TypeScript code that tries to check if a number x is odd using bits:
function isOdd(x: number): boolean {
  return x & 1 === 1;
}
medium
A. The bitwise AND operator has lower precedence than ===, causing wrong evaluation.
B. The function should use bitwise OR instead of AND.
C. The function should return a string, not boolean.
D. There is no error; the code works correctly.

Solution

  1. Step 1: Check operator precedence in expression

    Bitwise AND (&) has lower precedence than strict equality (===), so x & 1 === 1 is evaluated as x & (1 === 1).
  2. Step 2: Understand the evaluation result

    1 === 1 is true, which converts to 1, so expression becomes x & 1. This returns a number, not a boolean, causing unexpected behavior.
  3. Step 3: Fix the expression with parentheses

    Use parentheses: (x & 1) === 1 to ensure correct evaluation order.
  4. Final Answer:

    The bitwise AND operator has lower precedence than ===, causing wrong evaluation. -> Option A
  5. Quick Check:

    Use parentheses: (x & 1) === 1 [OK]
Hint: Use parentheses around bitwise operation before comparison [OK]
Common Mistakes:
  • Ignoring operator precedence
  • Using bitwise OR instead of AND
  • Returning wrong data type
5. You want to filter an array of numbers to keep only the even ones using bitwise operations in TypeScript. Which code snippet correctly achieves this?
const nums = [10, 15, 22, 33, 40];
const evens = nums.filter( /* your code here */ );
console.log(evens);
hard
A. nums.filter(num => (num & 1) === 1)
B. nums.filter(num => (num | 1) === 0)
C. nums.filter(num => (num & 1) === 0)
D. nums.filter(num => (num ^ 1) === 0)

Solution

  1. Step 1: Understand filtering condition for even numbers

    Even numbers have their least significant bit as 0, so (num & 1) === 0 checks for even numbers.
  2. Step 2: Apply filter with correct condition

    Using nums.filter(num => (num & 1) === 0) returns only even numbers from the array.
  3. Step 3: Verify output

    For [10, 15, 22, 33, 40], the filtered array is [10, 22, 40].
  4. Final Answer:

    nums.filter(num => (num & 1) === 0) -> Option C
  5. Quick Check:

    Filter even numbers with (num & 1) === 0 [OK]
Hint: Filter with (num & 1) === 0 to get even numbers [OK]
Common Mistakes:
  • Using bitwise OR or XOR incorrectly
  • Filtering for odd numbers instead of even
  • Missing parentheses causing wrong evaluation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard