Problem statement

https://binarysearch.com/problems/Target-Number-with-Operations-Sequel/

Solution

The idea is start from the end and go in the opposite direction. Each time we have even number, divide it by 2.

Complexity

It is O(log n) for time and O(1) for space.

Code

class Solution:
    def solve(self, x, y):
        steps = 0
        while True:
            if y <= x:
                return steps + (x - y)
            if y % 2 == 0:
                y //= 2
            else:
                y += 1
            steps += 1
        return steps