Medium · bits + arrays
Binary Representation
Print a positive integer in binary: 5 → 101. No strings allowed — the elegant path pops bits with % 2, stashes them in an array, and prints the array backwards.
At a glancePeel bits off with n % 2 into an array and print the array backwards — the bits come out least-significant first, so the reverse step is mandatory.
Problem
Input: one positive integer N (1 ≤ N ≤ 1023).
Output: the binary representation of N, without leading zeros.
Samples:
| Input | Output |
|---|---|
5 | 101 |
8 | 1000 |
Your solution
Custom input for "Run my input"
Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.
Stuck? Hints
Hint 1 — binary is just base-10 chopping
You already chop decimal digits with % 10 and / 10 (Sum of Digits). Binary chops bits with % 2 and / 2: 5 → 1, 2 → 0, 1 → 1, then 0 stops it. Popped order: 101 reversed is… already the answer here, but try 8.
Hint 2 — why 8 breaks the direct print
8 pops as 0, 0, 0, 1 — lowest bit first. Printing directly gives 0001; the answer is 1000. So store each bit in an array (bits[k++] = n % 2;), then loop from k-1 down to 0. The array size only needs ~10 slots for N ≤ 1023 (10 bits).
Solution (try it first!)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int bits[16];
int k = 0;
while (n > 0) {
bits[k++] = n % 2;
n /= 2;
}
for (int i = k - 1; i >= 0; i--) {
cout << bits[i];
}
cout << endl;
return 0;
}
This "stash then print backwards" trick is exactly how Reverse a Number works conceptually — the array just makes the reversal explicit. On a desktop compiler the same job is one line: cout << bitset<8>(n);. Stretch goal: octal (base 8 — change two characters) or any base up to 10.
Deep dive
Why this works
The same peel loop as decimal, with base 2 instead of 10. That proves base conversion is one algorithm with a parameter, not a family of algorithms.
The cost
O(log₂ n) — at most 32 iterations for an int.
Where it goes wrong
- Pushing bits and printing immediately gives them least-significant first. Collect, then print backwards.
n % 2on a negative number is negative in C++. Work with unsigned values or abs.
Next step
Count what you just extracted: Bit Count.
Two things to remember
- Base conversion is one loop with a parameter.
- Bits come out least-significant first — you must reverse.
🐞 This version fails — open it and try
Prints the bits least-significant first
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
while (n > 0) {
cout << n % 2;
n /= 2;
}
cout << endl;
return 0;
}