Skip to content

Latest commit

 

History

History
49 lines (45 loc) · 1.25 KB

File metadata and controls

49 lines (45 loc) · 1.25 KB

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