Print binary representation
Filed under Microsoft
Free read 1 of 3Ask if negative numbers should be represented in two's complement.
The question
Given an integer, print its binary representation.
Constraints
- Handle positive integers
- Do not use built-in format functions like bin()
- Output should be a string or printed sequence
Examples
- Input
- 5
- Output
- 101
- Why
- 5 in binary is 1*2^2 + 0*2^1 + 1*2^0.
Approach
Ask if negative numbers should be represented in two's complement.
Repeatedly take the number modulo 2 to get the last bit, then divide the number by 2 until it reaches 0.
Since the bits are extracted from least significant to most significant, reverse the result string before printing.
Solution
O(log N) time, O(log N) space
def to_binary(n):
if n == 0: return '0'
res = []
while n > 0:
res.append(str(n % 2))
n //= 2
return ''.join(res[::-1])
Tips
- What they are testing: Test with 0, 1, and large integers.
- Common mistake: Printing bits in reverse order or failing to handle the number 0 correctly.
Related Microsoft questions
Collected from public candidate posts and coding forums. Updated Nov 2026.