当前位置:网站首页>力扣6_1342. 将数字变成 0 的操作次数
力扣6_1342. 将数字变成 0 的操作次数
2022-07-08 00:39:00 【上课不要睡觉了】
给你一个非负整数 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
来源:力扣(LeetCode)
两种解法使用的原理均是根据二进制数的特性,根据所在位的0或1的情况确定对应的步骤数。
Java解法
class Solution {
public int numberOfSteps(int num) {
int ret = 0;
while (num > 0) {
ret += (num > 1 ? 1 : 0) + (num & 0x01);
//将&符号两边的数字转化成二进制,进行按位与运算
num >>= 1;
}
return ret;
}
}
Python解法
class Solution:
def numberOfSteps(self, num: int) -> int:
ans = 0
while num:
ans += num & 1
if num > 1:
ans += 1
num >>= 1
return ans
边栏推荐
- SQLite3 data storage location created by Android
- leetcode 873. Length of Longest Fibonacci Subsequence | 873. 最长的斐波那契子序列的长度
- From starfish OS' continued deflationary consumption of SFO, the value of SFO in the long run
- XXL job of distributed timed tasks
- 阿南的判断
- 【错误】加载h5权重出错AttributeError: ‘str‘ object has no attribute ‘decode‘
- Mouse event - event object
- C language -cmake cmakelists Txt tutorial
- #797div3 A---C
- 2022国内十大工业级三维视觉引导企业一览
猜你喜欢

Ml self realization /knn/ classification / weightlessness

Graphic network: uncover the principle behind TCP's four waves, combined with the example of boyfriend and girlfriend breaking up, which is easy to understand

JVM memory and garbage collection-3-object instantiation and memory layout

关于TXE和TC标志位的小知识

Remote Sensing投稿经验分享

很多小夥伴不太了解ORM框架的底層原理,這不,冰河帶你10分鐘手擼一個極簡版ORM框架(趕快收藏吧)

给刚入门或者准备转行网络工程师的朋友一些建议

adb工具介绍

C语言-Cmake-CMakeLists.txt教程

如何制作企业招聘二维码?
随机推荐
leetcode 866. Prime Palindrome | 866. 回文素数
burpsuite
In depth analysis of ArrayList source code, from the most basic capacity expansion principle, to the magic iterator and fast fail mechanism, you have everything you want!!!
Codeforces Round #643 (Div. 2)——B. Young Explorers
Graphic network: uncover the principle behind TCP's four waves, combined with the example of boyfriend and girlfriend breaking up, which is easy to understand
C language - modularization -clion (static library, dynamic library) use
Dataworks duty table
Reading notes of Clickhouse principle analysis and Application Practice (7)
ANSI / nema- mw- 1000-2020 magnetic iron wire standard Latest original
Remote Sensing投稿經驗分享
The circuit is shown in the figure, r1=2k Ω, r2=2k Ω, r3=4k Ω, rf=4k Ω. Find the expression of the relationship between output and input.
Codeforces Round #649 (Div. 2)——A. XXXXX
如何用Diffusion models做interpolation插值任务?——原理解析和代码实战
XXL job of distributed timed tasks
Remote Sensing投稿经验分享
How to make the conductive slip ring signal better
Introduction to grpc for cloud native application development
PB9.0 insert OLE control error repair tool
谈谈 SAP 系统的权限管控和事务记录功能的实现
Usage of hydraulic rotary joint