Fixed Width Binary
Return the binary form of the non-negative integer n as a string of exactly width characters, each 0 or 1, with the highest bit first. When the binary form of n is shorter than width, pad it with 0 characters on the left. n always fits in width bits, so nothing is ever cut off.
Example 1
n 5
width 8
returns "00000101"
5 is 101 in binary; padded on the left to 8 characters it becomes 00000101.
Example 2
n 0
width 3
returns "000"
0 has no 1 bits, so all three characters are 0.
Constraints
1 <= width <= 310 <= n < 2**width
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Bits problems
- Flip One BitBeginner
- Gray Code SequenceBeginner
- How Many Bits LongBeginner
- Keep the Low BitsBeginner
- Lowest Set BitBeginner
- Parity BitBeginner
- Read One BitBeginner
- Read a Binary StringBeginner