Leetcode-1342.将数字变成 0 的操作次数

282 阅读1分钟

题目

给一个非负整数num,如果num是偶数则除2,是奇数则-1,返回num到0需要多少步?

Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/nu… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题:

1.while循环

def stepto0(num):
    step=0 用于计步
    while num > 0:
        if num % 2 == 0:
            num = num / 2
        else:
            num = num - 1
        step += 1
    
    return step

2.递归

def stepto0(num):
    if num == 0:
        return 0
    else:
        if num % 2 == 0:
            num = num / 2
        else:
            num = num - 1
    return 1+stepto0(num)