1256. Encode Number π
SourceBiweekly Contest 13 Q1DifficultyMediumRating1561
Description
Given a non-negative integer num, Return its encoding string.
The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:
Example 1:
Input: num = 23 Output: "1000"
Example 2:
Input: num = 107 Output: "101100"
Constraints:
0 <= num <= 10^9
Solutions
Solution 1: Bit Manipulation
Thinking
The table is \(0,1,00,01,\ldots\), i.e. all binary strings in order. The bits of \(\textit{num}+1\) without the leading \(1\) are exactly the \(\textit{num}\)-th such string. \(\textit{num}\) reaches \(10^9\), so we cannot list them; one bit trick suffices.
We add one to \(\textit{num}\), then convert it to a binary string and remove the highest bit \(1\).
The time complexity is \(O(\log n)\), and the space complexity is \(O(\log n)\), where \(n\) is the size of \(\textit{num}\).
1 2 3 | |
1 2 3 4 5 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 | |
1 2 3 4 5 | |
