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 % 2produces 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-casen == 0to print0directly (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;0prints0).
Example: input 13 -> 1101.