PPractick

DSA interview question

Check Whether a Number Is Odd Using Bits

Easy · Algorithms · Topics: bit manipulation

The problem

A load balancer alternates requests between two server pools based on whether the request ID is odd or even. The check runs on every request and must be correct for negative IDs too, which some legacy clients send. n % 2 == 1 is a classic trap: in C++, -3 % 2 is -1, so negative odd numbers are misclassified. Looking at the least significant bit avoids both the division and the sign problem: in two's complement, a number is odd exactly when bit 0 is 1.

Example: 7 → odd; −4 → even.

Function signature

bool isOdd(int n);

Test cases

InputOutputExplanation
7odd111 ends in 1
10even1010 ends in 0
0even
-3oddTwo's complement ...1101 ends in 1, even though −3 % 2 is −1
-4even...1100

(Confirm: n is a 32-bit signed integer, possibly negative.)

How interviewers phrase it

Clarifying questions to ask

  1. Can n be negative?
  2. Must I avoid % and /? (That's the point of the exercise.)
  3. What should I return: a bool or the strings "odd"/"even"?

Follow-ups to expect

  1. "Why does n & 1 work?"
  2. "Why is n % 2 == 1 buggy?"
  3. "How do you check divisibility by 2^k?"
  4. "Is n & 1 really faster?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in