Problem Description
Given a non-negative integer num, return its encoding as a string. The encoding is hidden behind a secret function that can be deduced from the examples provided. In particular, you are given:
• Example 1:
Input: num = 23
Output: "1000"
• Example 2:
Input: num = 107
Output: "101100"
After analyzing the examples (and an image mapping that details the conversion), one can deduce that the secret encoding works by converting (num+1) to its binary representation and then removing the most significant bit. Note that, by definition, if num is 0, the encoded string should be "0".
Key Insights
- The encoding process is equivalent to generating the binary representation of (num + 1) and then dropping its leftmost (most significant) bit.
- If num is 0 then (0+1) in binary is "1", and after removing the first bit, the final encoded string is defined to be "0".
- The operation mainly involves binary manipulation, so the time complexity is proportional to the number of bits in num (O(log(num))).
Space and Time Complexity
Time Complexity: O(log(num))
Space Complexity: O(log(num))
Solution
The solution follows these steps:
- If num is 0, immediately return "0" because (0+1) in binary is "1", and dropping its first bit must be specially handled.
- Compute num+1.
- Convert num+1 to its binary string representation.
- Remove the leading character from this binary string. This is safe because for any num > 0, num+1 in binary always starts with '1'.
- Return the remaining substring as the encoded string.
The key data structure used is a string (to represent the binary number), and the main algorithmic idea is simple arithmetic and string manipulation based on properties of binary representation.