当前位置:网站首页>Daily question 1342 Number of operations to change the number to 0

Daily question 1342 Number of operations to change the number to 0

2022-07-05 05:42:00 A big pigeon

topic : Given num, If the current number is even , You need to divide it by 2 ; otherwise , subtract 1 . Ask for general num become 0 Required times .

Explain : Directly according to the meaning of the topic , Bit operation can improve computational efficiency

class Solution:
    def numberOfSteps(self, num: int) -> int:
        step = 0
        while num:
            if num&1: #num It's amazing , Equivalent to num%2 ==1
                num -= 1        
            else: 
                num = num>>1  # Equivalent to  num // 2       
            step += 1
        return step

 

原网站

版权声明
本文为[A big pigeon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140620422409.html