fork download
  1. from collections import deque
  2.  
  3. def getMinOperations(n):
  4. visited = set()
  5. queue = deque([(n, 0)]) # (current_value, operations)
  6.  
  7. while queue:
  8. num, steps = queue.popleft()
  9. if num == 0:
  10. return steps
  11. if num in visited:
  12. continue
  13. visited.add(num)
  14.  
  15. i = 0
  16. while (1 << i) <= n * 2: # try enough powers of 2
  17. power = 1 << i
  18. for next_num in (num - power, num + power):
  19. if 0 <= next_num < (1 << 20) and next_num not in visited:
  20. queue.append((next_num, steps + 1))
  21. i += 1
  22.  
  23.  
  24. print(getMinOperations(983017))
Success #stdin #stdout 3.74s 293108KB
stdin
Standard input is empty
stdout
6