Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2023/imperative-programming/2/a/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2023 Imperative programming 2 a Solution by
Codex 0 2026-10-25
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
}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. New to topics? Read the docs here!