Last active
July 8, 2020 11:57
-
-
Save Desolve/2370b48ca224bdc83884be2e66e770f2 to your computer and use it in GitHub Desktop.
1342 Number of Steps to Reduce a Number to Zero
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def numberOfSteps (self, num: int) -> int: | |
return bin(num).count('1') + len(bin(num)) - 3 | |
''' | |
# another solution | |
class Solution: | |
def numberOfSteps (self, num: int) -> int: | |
if num == 0: return 0 | |
res = 0 | |
while num != 0: | |
res += (num & 1) + 1 | |
num >>= 1 | |
return res - 1 | |
# from leetcode | |
class Solution: | |
def numberOfSteps (self, num: int) -> int: | |
step = 0 | |
while num != 0: | |
if num % 2 == 0: | |
num /= 2 | |
else: | |
num -= 1 | |
step += 1 | |
return step | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment