Encode Number — LeetCode 1256 Python Solution

MediumLeetCode PremiumBit ManipulationMathString
Problem
#1256
Reading time
2 min

The problem

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:

This statement is abridged. Read the full problem on LeetCode.

Example

Input
num = 23
Output
"1000"

Python solution

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

Complexity

MeasureComplexity
TimeO(\log n)
SpaceO(\log n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1256. Encode Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1256. Encode Number?
LeetCode 1256. Encode Number is rated Medium on LeetCode.
What is the time complexity of LeetCode 1256. Encode Number?
The Python solution on this page runs in O(\log n).
What is the space complexity of LeetCode 1256. Encode Number?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1256. Encode Number cover?
LeetCode 1256. Encode Number is tagged Bit Manipulation, Math and String on LeetCode.
Is LeetCode 1256. Encode Number a premium problem?
Yes. LeetCode 1256. Encode Number is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview