Skip to content

Instantly share code, notes, and snippets.

@anson-vandoren
Created February 25, 2021 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anson-vandoren/933faa2e2ec61a3b872d76c3dbd9079f to your computer and use it in GitHub Desktop.
Save anson-vandoren/933faa2e2ec61a3b872d76c3dbd9079f to your computer and use it in GitHub Desktop.
class Solution:
def brokenCalc(self, x: int, y: int) -> int:
if y < x:
return x - y
# find next power of 2
next_highest_power_of_two = 1
exp = 0
while next_highest_power_of_two < y / x:
next_highest_power_of_two <<= 1
exp += 1
steps_below_next_highest_power_of_two = x * next_highest_power_of_two - y
step_section = steps_below_next_highest_power_of_two >> exp
num_modulos = bin(steps_below_next_highest_power_of_two)[-exp:].count("1")
return exp + step_section + num_modulos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment