[Bit Operation-Simple] 1342. The number of operations to turn a number into 0 (bin()+bit_length())

[Title]
Give you a non-negative integer num, please return the number of steps required to turn it into 0. If the current number is even, you need to divide it by 2; otherwise, subtract 1.
[Example 1]
Input: num = 14
Output: 6
Explanation:
Step 1) 14 is an even number, divide by 2 to get 7.
Step 2) 7 is an odd number, subtract 1 to get 6.
Step 3) 6 is an even number, divide by 2 to get 3.
Step 4) 3 is an odd number, subtract 1 to get 2.
Step 5) 2 is an even number, divide by 2 to get 1.
Step 6) 1 is an odd number, subtract 1 to get 0.
[Example 2]
Input: num = 8
Output: 4
Explanation:
Step 1) 8 is an even number, divide by 2 to get 4.
Step 2) 4 is an even number, divide by 2 to get 2.
Step 3) 2 is an even number, divide by 2 to get 1.
Step 4) 1 is an odd number, subtract 1 to get 0.
[Example 3]
Input: num = 123
Output: 12
Prompt:
0 <= num <= 10^6
[Code]
[Python]
Insert picture description here

class Solution:
    def numberOfSteps (self, num: int) -> int:
        step=0
        while num:
            if num%2==0:
                num//=2
            else:
                num-=1
            step+=1
        return step

[Bit operation: bin function]
Insert picture description here

class Solution:
    def numberOfSteps (self, num: int) -> int:
        s = bin(num)[2:]
        res = len(s) + sum([int(i) for i in s]) - 1
        return res

[One line of code: bin()+bit_length()]

class Solution:
    def numberOfSteps (self, num: int) -> int:
        return num and (bin(num).count('1') + num.bit_length() - 1)

Guess you like

Origin blog.csdn.net/kz_java/article/details/115052391