1
# Runtime: 3027 ms (Top 7.32%) | Memory: 13.9 MB (Top 97.56%)3
def leastOpsExpressTarget(self, x, target):4
return self.cost(x, target)6
def cost(self, x, val):11
# either val > x / 2: we substract 1s12
state_1 = 2 * (x - val)13
# or val < x / 2: we divide once to 1 and we add enough 1s15
return min(state_1, state_2)17
# there is a maximum power of x that we can add18
p = int(log(val) // log(x))19
# and either x^p or x^(p+1) is the closest23
# x**(p+1) - val < val - x**p24
return min(p + self.cost(x, val - a), p + 1 + self.cost(x, b - val))26
return p + self.cost(x, val - a)