Decimal to Binary

easy Number Problems

Problem

Read a non-negative integer and print its binary form (base 2). Example: 10 is 1010.

Constraints

  • 0 <= n <= 2^31 - 1

Examples

Input

10

Output

1010

Solutions

Best approachTime O(log n)Space O(log n)

We divide the number by 2 again and again. The remainders are the binary digits, from the last digit to the first. Reading them in reverse gives the binary number.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Convert a decimal number to binary.
 * Input   : One non-negative integer.
 * Output  : The binary form.
 * Approach: Divide by 2 and collect the remainders.
 * Time    : O(log n)
 * Space   : O(log n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        long number = new Scanner(System.in).nextLong();

        // Step 1: Zero is written as 0. The loop below would write nothing, so we handle 0 first.
        if (number == 0) {
            System.out.println("0");
            return;
        }

        // Step 2: Collect the binary digits here. We get them from the last digit to the first digit.
        StringBuilder bits = new StringBuilder();

        // Step 3: Repeat until the number is 0.
        while (number > 0) {
            // Step 4: The remainder of the division by 2 is the next binary digit. Example: 10 % 2 = 0.
            bits.append(number % 2);

            // Step 5: Divide by 2 to go to the next digit. Example: 10 / 2 = 5.
            number = number / 2;
        }

        // Step 6: The digits are in reverse order, so we reverse them before we print.
        System.out.println(bits.reverse());
    }
}
Hints (2)
  1. What are the possible remainders when you divide by 2?
  2. The first remainder is the last binary digit.