Write the field out in binary
A diagnostics screen prints a flags field as ones and zeros so an engineer can see at a glance which switches are on.
- Return the binary digits, most significant first.
- No leading zeros — except zero itself, which is written "0".
- The value is never negative.
toBinary(flags: int) → string
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
std::string toBinary(int flags) {
}
Worked examples
| Call | Result |
|---|---|
toBinary(5) | std::string("101") |
toBinary(0) | std::string("0") |
toBinary(1) | std::string("1") |
toBinary(8) | std::string("1000") |
Hint
Peel off the lowest bit with a mask, shift down, and repeat. The digits come out backwards, so reverse them at the end.
Reference solution in C++
std::string toBinary(int flags) {
if (flags == 0) return "0";
std::string digits;
int field = flags;
while (field > 0) {
digits = static_cast<char>('0' + (field & 1)) + digits;
field >>= 1;
}
return digits;
}