LeetCode 1256. Encode Number Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1256. Encode Number

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:

    <li><code>0 &lt;= num &lt;= 10^9</code></li>
    

Solutions

Solution 1: Bit Manipulation

We add one to 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 num.

PythonJavaC++GoTypeScript
class Solution: def encode(self, num: int) -> str: return bin(num + 1)[3:](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !