OlveraeUNSW
Back to problems
COMP2521

Stack: Decimal to Binary

Stack: decimal to binary using a stack

Read a non-negative integer n and use a stack to convert it to binary and print it.

Method: repeatedly take n % 2 (one binary digit), push it, then n /= 2, until n == 0; finally pop them all and print.

Complete printBinary.

Why a stack: n % 2 produces digits from least to most significant, but binary is written most-significant first. Pushing then popping reverses the order back to correct — a classic use of a stack's reversing property.
Pitfall: special-case n == 0 to print 0 directly (otherwise the loop never runs and nothing prints).

Input

  • One line: non-negative integer n (0 ≤ n ≤ 2000000000).

Output

  • One line: the binary representation of n (no leading zeros; 0 prints 0).

Example: input 13 -> 1101.

Samples

stdin
13
expected
1101
stdin
0
expected
0
c-dcc
14