Convert a non-negative decimal integer to its binary string (e.g. 13 -> "1101").
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()).
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:]Base conversion underlies bitmask debugging, protocol encoding, and understanding how numbers are stored — foundational systems knowledge.
A candidate appends bits and forgets to reverse, so 13 prints "1011". What is the fix?