TechByteByByte

Decimal to Binary Conversion (and Back) - Java

A medium QA/automation coding interview question: decimal to Binary Conversion (and Back), with a full Java walkthrough, dry run, and common interviewer follow-ups.

#Math#Bitwise Operations#Number Systems#Medium#Java

Category: Medium | Concepts used: Division/modulo digit extraction, built-in conversion methods


Problem Statement

Part A: Convert a decimal (base-10) number to its binary (base-2) string representation. Part B: Convert a binary string back to its decimal value.

Input : 10 (decimal)      Output: "1010" (binary)
Input : "1010" (binary)    Output: 10 (decimal)

Examples (with edge scenarios)

#InputOutputWhy
110 → binary"1010"Standard conversion
20 → binary"0"Zero is a special case — the loop-based approach would produce an empty string otherwise
31 → binary"1"Smallest positive case
4"1010" → decimal10Reverse direction
5-5 → binaryNeeds clarificationNegative numbers require deciding: two’s complement representation, or a ”-” prefixed sign-magnitude form?

Common Fresher Mistake

MistakeWhat happensFix
Not handling n == 0 specially in a manual loop-based conversionLoop while (n > 0) never executes, producing an empty string instead of "0"Add an explicit check: if n == 0, return "0" directly
Forgetting the binary digits come out in reverse order when built via modulo/divisionProduces a backward-looking binary string (e.g., "0101" instead of "1010")Reverse the collected digits at the end, or prepend instead of appending

Before You Code: Clarify the Contract

Before choosing an algorithm, confirm whether zero and negative values are allowed, how large the input can be, and what should happen when an arithmetic result exceeds the chosen Java type. The examples use the contract stated in this article, but an interview answer should say these assumptions aloud.

Analogy: Pairing Cards & The Step Ladder

  • Decimal to Binary (Solution 1 - Pairing Cards): Imagine you have a stack of 10 playing cards (n = 10):
    • You divide the stack in half: you get 5 pairs with 0 leftover cards (10 % 2 = 0). You write down 0 on a sticky note.
    • You now have 5 pairs. You divide them in half: you get 2 groups of pairs with 1 leftover pair (5 % 2 = 1). You write down 1.
    • You now have 2 groups. Divide in half: you get 1 group of 4 with 0 leftovers (2 % 2 = 0). You write down 0.
    • You have 1 group. Divide in half: you get 0 groups with 1 leftover (1 % 2 = 1). You write down 1.
    • You stop since no cards are left. Reading your sticky notes from last to first (reversed) gives you 1010!
  • Binary to Decimal (Part B - The Step Ladder): Imagine a step ladder where each rung represents a power of 2:
    • Rung 0 (bottom) is worth 1 step.
    • Rung 1 is worth 2 steps.
    • Rung 2 is worth 4 steps.
    • Rung 3 (top) is worth 8 steps.
    • If you look at "1010", you see a '1' flag on Rung 3 and Rung 1. You add their heights together: 8 + 2 = 10 steps!

Solution 1 — Manual Conversion Using Modulo and Division

Intuition

To convert to binary, repeatedly divide the number by 2 and record the remainder (0 or 1) each time — this is the standard “repeated division” technique for base conversion. Since each remainder comes out least-significant digit first, the digits need to be reversed (or prepended) to get the correct final order.

public class DecimalToBinaryManual {
    public static String toBinary(int n) {
        if (n == 0) {
            return "0"; // special case
        }

StringBuilder binary = new StringBuilder();
        while (n > 0) {
            int remainder = n % 2;
            binary.append(remainder);  // digits collected in reverse order
            n = n / 2;
        }

return binary.reverse().toString(); // flip to correct order
    }

public static void main(String[] args) {
        System.out.println(toBinary(10)); // 1010
        System.out.println(toBinary(0));   // 0
        System.out.println(toBinary(1));    // 1
    }
}

Output:

1010
0
1

Dry Run (n = 10)

n=10, binary=""

n%2=0, binary="0", n=10/2=5
n%2=1, binary="01", n=5/2=2
n%2=0, binary="010", n=2/2=1
n%2=1, binary="0101", n=1/2=0

Reverse "0101" -> "1010"
Final: "1010"

Interviewer’s take

This is exactly the expected manual solution — shows understanding of how base conversion actually works under the hood (repeated division and remainder collection). The n == 0 special case and the final reversal are the two details interviewers watch for.

Follow-up questions you might get:

  • “Why do the digits come out in reverse order?” → Because the first remainder we compute corresponds to the least significant bit (rightmost digit), while we need to display the most significant bit first — so a reversal (or building the string from the front) is required.
  • “Is there a built-in way to do this in Java?” → leads to Solution 2.

Solution 2 — Using Integer.toBinaryString() (Built-in, Practical)

Intuition

Java already provides a purpose-built method for exactly this conversion — no need to reimplement the repeated-division logic manually in real code.

public class DecimalToBinaryBuiltIn {
    public static void main(String[] args) {
        System.out.println(Integer.toBinaryString(10)); // 1010
        System.out.println(Integer.toBinaryString(0));   // 0
    }
}

Output:

1010
0

Interviewer’s take

Perfectly fine for real-world code — but if the interviewer is testing understanding of number systems (rather than API familiarity), they’ll likely want to see the manual version (Solution 1) first, then mention this as the “real-world shortcut.” Worth noting: Integer.toBinaryString() represents negative numbers using 32-bit two’s complement, which is worth mentioning if negative inputs come up.


Part B — Binary String to Decimal

Intuition

Each digit in a binary string represents a power of 2, based on its position from the right (rightmost = 2⁰, next = 2¹, and so on). To convert back to decimal, walk through the string, and for every '1' digit encountered, add the corresponding power-of-2 value to a running total.

public class BinaryToDecimal {
    public static int toDecimal(String binary) {
        int decimal = 0;
        int power = 0;

// process from the rightmost character to the leftmost
        for (int i = binary.length() - 1; i >= 0; i--) {
            if (binary.charAt(i) == '1') {
                decimal += Math.pow(2, power);
            }
            power++;
        }
        return decimal;
    }

public static void main(String[] args) {
        System.out.println(toDecimal("1010")); // 10
        System.out.println(toDecimal("0"));      // 0
        System.out.println(toDecimal("1"));       // 1
    }
}

Output:

10
0
1

Dry Run (binary = “1010”)

i=3(last char '0'): power=0, '0'!='1' -> skip, power=1
i=2(char '1'):       power=1, MATCH -> decimal += 2^1=2 -> decimal=2, power=2
i=1(char '0'):       power=2, skip, power=3
i=0(char '1'):       power=3, MATCH -> decimal += 2^3=8 -> decimal=2+8=10, power=4

Final: decimal=10

Interviewer’s take

Correct manual approach. Java also offers Integer.parseInt(binaryString, 2) as a built-in shortcut — mention it as the practical real-world equivalent, similar to Part A’s built-in alternative.

Follow-up questions you might get:

  • “What’s the built-in way to do this?”Integer.parseInt("1010", 2) — the second argument tells Java to interpret the string in base 2.

📊 Visual Flowchart (Decimal to Binary)

graph TD
    Start["Input Decimal n"] --> ZeroCheck{"n == 0?"}
    ZeroCheck -->|Yes| RetZero["Return '0'"]
    ZeroCheck -->|No| InitSB["Initialize StringBuilder binary"]
    InitSB --> Loop{"n > 0?"}
    Loop -->|Yes| Mod["rem = n % 2"]
    Mod --> Append["binary.append(rem)"]
    Append --> Div["n /= 2"]
    Div --> Loop
    Loop -->|No| Rev["binary.reverse()"]
    Rev --> End["Return binary string"]

Final Verdict — Which Solution Should You Give?

  • Show the manual approach (Solution 1 / Part B manual) first to prove understanding of how number systems work.
  • Mention the built-in methods (Integer.toBinaryString(), Integer.parseInt(str, 2)) as the practical, real-world shortcuts.

Quick Recap

DirectionManual ApproachBuilt-in Method
Decimal → BinaryRepeated division by 2, collect remainders, reverseInteger.toBinaryString(n)
Binary → DecimalSum of 2^position for each '1' digitInteger.parseInt(str, 2)
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed