Decimal to Binary in Java: Explanation & Practice

Convert decimal number to binary

Problem summary

Write a program that converts a decimal number to its binary representation.

Starter code

public class Main {
    public static void main(String[] args) {
        int decimal = 13; // Test case 1
        
        // Convert to binary
        // Print: Binary: <result>
    }
}

Expected output and test cases

  • 13 in binary
    Binary: 1101
  • 10 in binary
    Binary: 1010
  • 1 in binary
    Binary: 1

Hints

  1. Divide by 2 and collect remainders
  2. Build binary string from right to left
  3. Or use StringBuilder and reverse at end

Related Control Flow exercises

Practice all Control Flow exercises · Run this idea in the Java compiler