1194. Six-Bit Encoder
A mail gateway must turn printable text into a form that is safe for plain-text channels. Take the ASCII bytes of text, pack every 3 bytes into 24 bits, and split those bits into four 6-bit values. Each value indexes the alphabet A-Z, a-z, 0-9, +, / (in that order, so 0 is A and 63 is /).
A final group of 1 byte is padded with zero bits, writes 2 characters and is followed by ==; a final group of 2 bytes writes 3 characters and is followed by =. Return the encoded string, which is empty for empty text.
One pass with shifts and masks does it in O(n) time and O(n) space for the output. Write the bit manipulation yourself rather than relying on a library encoder.
Example 1
- Input:
- text = "Man"
- Output:
- "TWFu"
- Explanation:
The three bytes 77, 97, 110 pack into 24 bits that split into the indices 19, 22, 5, 46, giving TWFu.
Example 2
- Input:
- text = "Ma"
- Output:
- "TWE="
- Explanation:
Two bytes leave a partial group, so three characters are written followed by one equals sign.
Example 3
- Input:
- text = "M"
- Output:
- "TQ=="
- Explanation:
One byte writes two characters followed by two equals signs.
Constraints
0 ≤ text.length ≤ 3000
text is printable ASCII
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)