TreeviewCopyright © aleen42 all right reserved, powered by aleen42

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

https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-to-zero/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-08-21 15:00:22
 * @LastEditTime: 2020-08-21 15:00:39
 * @Description: https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-to-zero/
 * @FilePath: \leetcode-googtech\#1342. Number of Steps to Reduce a Number to Zero\Solution.java
 * @WebSite: https://algorithm.show/
 */

class Solution {
    public int numberOfSteps (int num) {
        int steps = 0;
        while(num > 0) {
            num = num % 2 == 0 ? num / 2 : num - 1;
            steps++;
        }
        return steps;
    }
}

Python

'''
Author: Goog Tech
Date: 2020-08-21 15:00:28
LastEditTime: 2020-08-21 15:00:57
Description: https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-to-zero/
FilePath: \leetcode-googtech\#1342. Number of Steps to Reduce a Number to Zero\Solution.py
WebSite: https://algorithm.show/
'''
class Solution(object):
    def numberOfSteps (self, num):
        """
        :type num: int
        :rtype: int
        """
        steps = 0
        while num > 0:
            num = num / 2 if num % 2 == 0 else num - 1
            steps += 1
        return steps
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""