= Solution
Repeated <integer division> by two generates the <binary digits> from least significant to most significant. Reverse the accumulated characters once, and treat zero separately.
``
def binaryCon(n: Int): String = {
require(n >= 0, "n must be nonnegative")
if (n == 0) return "0"
var remaining = n
val digits = new StringBuilder
while (remaining > 0) {
digits.append(if (remaining % 2 == 0) '0' else '1')
remaining /= 2
}
digits.reverse.toString
}
``
\b[Zero produces `"0"`; positive inputs produce a <binary number> without leading zeros.] No library routine performs the number-to-base conversion. Appending to the builder and reversing once gives linear work in the number of <binary digits> and uses that much output storage.
Back to article page