Minimum One Bit Operations to Make Integers Zero — LeetCode 1611 Python Solution

HardBit ManipulationMemoizationDynamic Programming
Problem
#1611
Reading time
2 min

The problem

Given an integer n, you must transform it into 0 using the following operations any number of times: Change the rightmost (0th) bit in the binary representation of n. Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.

Example

Input
n = 3
Output
2
Explanation
The binary representation of 3 is "11".

Python solution

Python
class Solution:
    def minimumOneBitOperations(self, n: int) -> int:
        ans = 0
        while n:
            ans ^= n
            n >>= 1
        return ans

Complexity

MeasureComplexity
TimeO(\log n), where n is the integer given in the problem
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1611. Minimum One Bit Operations to Make Integers Zero is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

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 1611. Minimum One Bit Operations to Make Integers Zero?
LeetCode 1611. Minimum One Bit Operations to Make Integers Zero is rated Hard on LeetCode.
What is the time complexity of LeetCode 1611. Minimum One Bit Operations to Make Integers Zero?
The Python solution on this page runs in O(\log n), where n is the integer given in the problem.
What is the space complexity of LeetCode 1611. Minimum One Bit Operations to Make Integers Zero?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1611. Minimum One Bit Operations to Make Integers Zero cover?
LeetCode 1611. Minimum One Bit Operations to Make Integers Zero is tagged Bit Manipulation, Memoization and Dynamic Programming on LeetCode.

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