LeetCode 1342. 将数字变成 0 的操作次数 Number of Steps to Reduce a Number to Zero

简介: LeetCode 1342. 将数字变成 0 的操作次数 Number of Steps to Reduce a Number to Zero

LeetCode 1342. 将数字变成 0 的操作次数 Number of Steps to Reduce a Number to Zero


Table of Contents

中文版:

英文版:

My answer:

解题报告:

中文版:

给你一个非负整数 num ,请你返回将它变成 0 所需要的步数。 如果当前数字是偶数,你需要把它除以 2 ;否则,减去 1 。

示例 1:

输入:num = 14

输出:6

解释:

步骤 1) 14 是偶数,除以 2 得到 7 。

步骤 2) 7 是奇数,减 1 得到 6 。

步骤 3) 6 是偶数,除以 2 得到 3 。

步骤 4) 3 是奇数,减 1 得到 2 。

步骤 5) 2 是偶数,除以 2 得到 1 。

步骤 6) 1 是奇数,减 1 得到 0 。

示例 2:

输入:num = 8

输出:4

解释:

步骤 1) 8 是偶数,除以 2 得到 4 。

步骤 2) 4 是偶数,除以 2 得到 2 。

步骤 3) 2 是偶数,除以 2 得到 1 。

步骤 4) 1 是奇数,减 1 得到 0 。

示例 3:

输入:num = 123

输出:12

 

提示:

0 <= num <= 10^6

英文版:

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.
Example 1:
Input: num = 14
Output: 6
Explanation:  
Step 1) 14 is even; divide by 2 and obtain 7.  
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.  
Step 4) 3 is odd; subtract 1 and obtain 2.  
Step 5) 2 is even; divide by 2 and obtain 1.  
Step 6) 1 is odd; subtract 1 and obtain 0.
Example 2:
Input: num = 8
Output: 4
Explanation:  
Step 1) 8 is even; divide by 2 and obtain 4.  
Step 2) 4 is even; divide by 2 and obtain 2.  
Step 3) 2 is even; divide by 2 and obtain 1.  
Step 4) 1 is odd; subtract 1 and obtain 0.
Example 3:
Input: num = 123
Output: 12
Constraints:
0 <= num <= 10^6

My answer:

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

解题报告:

本题目较简单,直接模拟题目中给出的算法即可。

相关文章
|
6月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
64 1
|
4月前
|
机器学习/深度学习 算法 测试技术
【单调栈】LeetCode:2818操作使得分最大
【单调栈】LeetCode:2818操作使得分最大
|
4月前
|
算法 测试技术 C#
【贪心算法】【中位贪心】LeetCode:100123.执行操作使频率分数最大
【贪心算法】【中位贪心】LeetCode:100123.执行操作使频率分数最大
|
4月前
leetcode-1441:用栈操作构建数组
leetcode-1441:用栈操作构建数组
21 0
|
4月前
|
Go
golang力扣leetcode 701. 二叉搜索树中的插入操作
golang力扣leetcode 701. 二叉搜索树中的插入操作
16 0
|
5月前
[leetcode] 2530. 执行 K 次操作后的最大分数 M
[leetcode] 2530. 执行 K 次操作后的最大分数 M
|
5月前
|
算法 测试技术 C++
【贪心算法】【中位贪心】LeetCode:100123.执行操作使频率分数最大
【贪心算法】【中位贪心】LeetCode:100123.执行操作使频率分数最大
|
6月前
|
算法
代码随想录算法训练营第二十一天 | LeetCode 235. 二叉搜索树的最近公共祖先、701. 二叉搜索树中的插入操作、450. 删除二叉搜索树中的节点
代码随想录算法训练营第二十一天 | LeetCode 235. 二叉搜索树的最近公共祖先、701. 二叉搜索树中的插入操作、450. 删除二叉搜索树中的节点
45 0
|
6月前
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
21 0
字符串解码(力扣 394)Java栈操作
给定一个经过编码的字符串,返回它解码后的字符串。
112 0

热门文章

最新文章