Convert decimal to binary
Convert a non-negative decimal integer to its binary representation without using Convert.ToString.
Course progress
Problem 18 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
number = 42
Expected output
101010
What is happening?
42 equals 32 + 8 + 2, so the 32, 8, and 2 bit positions are set. That produces the binary digits 101010.
Solution strategy
Build the right mental model
Repeatedly divide by 2 and write each remainder from the end of a buffer toward the front. Handle zero as a special case.
Core concepts
number systems · division
Complexity
Time O(log n), space O(log n).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for decimal-to-binary
using System;
class Program
{
static string ToBinary(int number)
{
if (number < 0) throw new ArgumentOutOfRangeException("number");
if (number == 0) return "0";
char[] bits = new char[32];
int write = bits.Length;
while (number > 0)
{
bits[--write] = (char)('0' + number % 2);
number /= 2;
}
return new string(bits, write, bits.Length - write);
}
static void Main()
{
Console.WriteLine(ToBinary(42));
}
}Knowledge check
Questions students often ask
What is the main idea behind convert decimal to binary?
Repeatedly divide by 2 and write each remainder from the end of a buffer toward the front. Handle zero as a special case.
What is the time and space complexity of this solution?
Time O(log n), space O(log n).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.