DSA interview question
A network tool displays packet header fields as raw bits and lets engineers type bit patterns back in. You need two helpers: toBinary(n) shows the exact 32 bits a signed int is stored as, and fromBinary(s) turns a bit string (most significant bit first) back into the int. Negative numbers are the interesting part. Computers store them in two's complement, so −1 is all ones and INT_MIN is a lone sign bit. Writing these helpers exercises the basic toolkit behind every bit-manipulation problem: shifts, masks, and the difference between signed and unsigned views of the same bits.
Example: toBinary(13) → 0000 0000 0000 0000 0000 0000 0000 1101; fromBinary("1101") → 13.
string toBinary(int n); // exactly 32 characters, most significant bit first
int fromBinary(const string& s); // 1 to 32 bits, most significant first; 32 bits may encode a negative
| Input | Output | Explanation |
|---|---|---|
toBinary(13) | 0000 0000 0000 0000 0000 0000 0000 1101 | 8 + 4 + 1 (spaces added for readability) |
toBinary(-1) | 1111 1111 1111 1111 1111 1111 1111 1111 | Two's complement of −1 is all ones |
toBinary(0) | 0000 0000 0000 0000 0000 0000 0000 0000 | |
toBinary(INT_MIN) | 1000 0000 0000 0000 0000 0000 0000 0000 | Only the sign bit |
fromBinary("1101") | 13 | |
fromBinary of 32 ones | -1 |
(Confirm: ints are 32-bit two's complement; toBinary always returns 32 characters; fromBinary reads its input most significant bit first.)
n & (n − 1) and n & −n do?"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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in