โ† Microsoft questions

Print binary representation

Filed under Microsoft

Free read 1 of 3

Ask 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

  1. Ask if negative numbers should be represented in two's complement.

Solution

O(log N) time, O(log N) space

Python
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.