当前位置:网站首页>力扣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
边栏推荐
- How to make enterprise recruitment QR code?
- CV2 read video - and save image or video
- 神经网络与深度学习-5- 感知机-PyTorch
- Ml self realization / linear regression / multivariable
- Urban land use distribution data / urban functional zoning distribution data / urban POI points of interest / vegetation type distribution
- 阿锅鱼的大度
- Redisson distributed lock unlocking exception
- Codeforces Round #643 (Div. 2)——B. Young Explorers
- Version 2.0 of tapdata, the open source live data platform, has been released
- 阿南的判断
猜你喜欢
Introduction to ADB tools
leetcode 866. Prime Palindrome | 866. 回文素数
Ml self realization /knn/ classification / weightlessness
关于TXE和TC标志位的小知识
C语言-模块化-Clion(静态库,动态库)使用
Ml backward propagation
The function of carbon brush slip ring in generator
进程和线程的退出
Introduction à l'outil nmap et aux commandes communes
Optimization of ecological | Lake Warehouse Integration: gbase 8A MPP + xeos
随机推荐
Voice of users | winter goes and spring comes, waiting for flowers to bloom -- on gbase 8A learning comprehension
剑指 Offer II 041. 滑动窗口的平均值
[recommendation system paper reading] recommendation simulation user feedback based on Reinforcement Learning
What are the types of system tests? Let me introduce them to you
Matlab r2021b installing libsvm
Analysis ideas after discovering that the on duty equipment is attacked
COMSOL --- construction of micro resistance beam model --- final temperature distribution and deformation --- addition of materials
阿锅鱼的大度
Dataworks duty table
Optimization of ecological | Lake Warehouse Integration: gbase 8A MPP + xeos
Can you write the software test questions?
Usage of hydraulic rotary joint
进程和线程的退出
关于TXE和TC标志位的小知识
PB9.0 insert OLE control error repair tool
QML fonts use pixelsize to adapt to the interface
谈谈 SAP iRPA Studio 创建的本地项目的云端部署问题
《ClickHouse原理解析与应用实践》读书笔记(7)
鼠标事件-事件对象
List of top ten domestic industrial 3D visual guidance enterprises in 2022