← Back to libraryQuestion 80 of 273
⌨️Java CodingIntermediate

Convert a Decimal Number to Binary

📌 Definition:

Convert a non-negative decimal integer to its binary string (e.g. 13 -> "1101").

📖 Detailed Explanation:

Repeatedly take n % 2 (the next least-significant bit) and prepend it, then divide n by 2, until n is zero. Because bits are produced least-significant first, build the string in reverse. O(log n). Built-ins exist (Integer.toBinaryString, bin()).

💻 Solutions:
public static String toBinary(int n) {
    if (n == 0) return "0";
    StringBuilder sb = new StringBuilder();
    while (n > 0) { sb.append(n % 2); n /= 2; }
    return sb.reverse().toString();
}
function toBinary(n) {
  if (n === 0) return '0';
  let out = '';
  while (n > 0) { out = (n % 2) + out; n = Math.floor(n / 2); }
  return out;
  // built-in: n.toString(2)
}
def to_binary(n):
    if n == 0:
        return '0'
    bits = ''
    while n > 0:
        bits = str(n % 2) + bits
        n //= 2
    return bits  # or bin(n)[2:]
🔑 Key Points:
  • n % 2 gives the next bit, n /= 2 shifts
  • Bits come out LSB-first — reverse them
  • Handle n == 0 -> "0"
  • Built-ins: Integer.toBinaryString / bin()
🌍 Real-World Example:

Base conversion underlies bitmask debugging, protocol encoding, and understanding how numbers are stored — foundational systems knowledge.

🎯 Scenario-Based Interview Question:

A candidate appends bits and forgets to reverse, so 13 prints "1011". What is the fix?