Decimal to binary
Decimal to binary is a easy bit manipulation problem solved with the basics pattern.
The best approach, bit test from the highest set bit, runs in O(log n) time and O(log n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from repeated division up.
Problem
Convert a positive integer n to its binary representation as a string, without using a library conversion.
Examples
Example 1
- Input
n = 13- Output
"1101"- Why
- 8 + 4 + 1.
Example 2
- Input
n = 1- Output
"1"
Constraints
1 <= n <= 10^9
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Repeated division | O(log n) | O(log n) |
| Bit test from the highest set bit | O(log n) | O(log n) |
1Repeated division
O(log n)O(log n)Take n % 2 as the next bit, divide by 2, repeat, then reverse the collected bits.
- While n > 0: append n % 2; n /= 2.
- Reverse.
class Solution {
static String decToBinary(int n) {
if (n == 0) return "0";
StringBuilder sb = new StringBuilder();
while (n > 0) {
sb.append(n % 2);
n /= 2;
}
return sb.reverse().toString();
}
}class Solution:
def decToBinary(self, n: int) -> str:
if n == 0:
return "0"
sb = []
while n > 0:
sb.append(str(n % 2))
n //= 2
return "".join(reversed(sb))class Solution {
public:
string decToBinary(int n) {
if (n == 0) return "0";
string sb;
while (n > 0) {
sb += char('0' + n % 2);
n /= 2;
}
reverse(sb.begin(), sb.end());
return sb;
}
};function decToBinary(n) {
if (n === 0) return "0";
const sb = [];
while (n > 0) {
sb.push(n % 2);
n = Math.floor(n / 2);
}
return sb.reverse().join('');
}2Bit test from the highest set bit
O(log n)O(log n)Find the highest set bit, then test each bit from there down with (n >> i) & 1. No reversal needed.
- hi = 31 - Integer.numberOfLeadingZeros(n).
- For i from hi down to 0: append (n >> i) & 1.
class Solution {
static String decToBinary(int n) {
if (n == 0) return "0";
StringBuilder sb = new StringBuilder();
for (int i = 31 - Integer.numberOfLeadingZeros(n); i >= 0; i--) sb.append((n >> i) & 1);
return sb.toString();
}
}class Solution:
def decToBinary(self, n: int) -> str:
if n == 0:
return "0"
sb = []
for i in range(n.bit_length() - 1, -1, -1):
sb.append(str((n >> i) & 1))
return "".join(sb)class Solution {
public:
string decToBinary(int n) {
if (n == 0) return "0";
string sb;
for (int i = 31 - __builtin_clz(n); i >= 0; i--) sb += char('0' + ((n >> i) & 1));
return sb;
}
};function decToBinary(n) {
if (n === 0) return "0";
let sb = '';
for (let i = 31 - Math.clz32(n); i >= 0; i--) sb += (n >> i) & 1;
return sb;
}Edge cases to test
- Powers of two (a single 1 followed by zeros)
- n = 0 if allowed ("0")
Hints
Hint 1
n % 2 is the lowest bit; n / 2 (or n >> 1) drops it. Collect bits from lowest to highest, then reverse.
FAQ
What is the best time complexity for Decimal to binary?
Bit test from the highest set bit runs in O(log n) time and O(log n) extra space.
Which pattern does Decimal to binary use?
It is a bit manipulation problem that uses the basics pattern. Other problems with the same pattern: Convert Binary Number in a Linked List to Integer, K-th Bit is Set or Not, Odd or Even.
Is there a brute force solution for Decimal to binary?
Yes. Repeated division takes O(log n) time and O(log n) space. Take n % 2 as the next bit, divide by 2, repeat, then reverse the collected bits.
Which edge cases should I test for Decimal to binary?
Powers of two (a single 1 followed by zeros); n = 0 if allowed ("0").