bit manipulation
]
Leetcode 1342. Number of Steps to Reduce a Number to Zero
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero
The straightforward solution for this problem is to just simulate the process: if we see even number we divide it by 2 and if we see odd number, we subtract 1.
Complexity: time complexity of this solution is O(20) = O(1)
, because length of number will always be no more than 20
. Space complexity is also O(1)
class Solution:
def numberOfSteps (self, num):
steps = 0
while num:
num = num&1 if num & 1 else num>>1
steps += 1
return steps
Oneliner
We can also notice, that each step we make with even number decrease its binary length by 1
and each step with odd number removes one 1
from binary representation. So final answer will be binary length of number + number of ones we have and minus 1
, because in the end we have number 0
with length 1
.
Complexity: time and space complexity is still O(1)
, however here we have some potential to improve: there are more efficient ways to count binary length of number and to count number of ones in binary representation.
See for example problem 191. Number of 1 Bits for more efficient ways to find number of 1
bits.
https://leetcode.com/problems/number-of-1-bits/discuss/1044775/Python-n-and-(n-1)-trick-%2B-even-faster-explained
return len(bin(num)) + bin(num).count("1") - 3
If you like the solution, you can upvote it on leetcode discussion section: Problem 1342