Easy+ Ā· base conversion

Decimal to Binary

Convert a decimal number to binary with nothing but % 2 and / 2. The single most common interview warm-up after Fibonacci.

Problem

Input: one integer n (0 ≤ n ≤ 10⁹).

Output: the binary representation of n, with no leading zeros (0 prints as 0).

Sample:

InputOutput
5101
25511111111

Your solution

Program.cs — your solution
Custom input for "Run my input"

Judging runs entirely in your browser against hidden tests. Your code is saved locally as you type. Ctrl+Enter judges.

Stuck? Hints

Hint 1 — the two operations

n % 2 is the LAST bit; n / 2 drops it. Either collect the bits and reverse them, or prepend each new bit to a string.

Hint 2 — the zero trap

The loop while (n > 0) never runs for n = 0, so you would print nothing. Handle 0 first (it prints as 0).

Solution (try first!)
int n = int.Parse(Console.ReadLine());
if (n == 0) { Console.WriteLine("0"); return; }
string bits = "";
while (n > 0) { bits = (n % 2) + bits; n = n / 2; }
Console.WriteLine(bits);

Prepending to a string is O(n²) for huge inputs — the string vs StringBuilder article explains when that matters. Next: Count the Primes.