滚蛋吧,2021
给你一个非负整数 num ,请你返回将它变成 0 所需要的步数。 如果当前数字是偶数,你需要把它除以 2 ;否则,减去 1 。
初级模拟 无任何技巧
class Solution {
public int numberOfSteps(int num) {
int count=0;
while(num!=0){
count++;
if(num%2==1){
num=num-1;
}else{
num=num/2;
}
}
return count;
}
}
三叶大神的精简版
算法也就图一乐,真题姐还得看三叶
原文链接:https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-to-zero/solution/gong-shui-san-xie-note-bie-pian-yi-ti-sh-85fb/
class Solution {
public int numberOfSteps(int num) {
int ans = 0;
while (num != 0 && ++ans >= 0) num = num % 2 == 0 ? num / 2 : num - 1;
return ans;
}
}
# 注释解释版
class Solution {
public int numberOfSteps(int num) {
int ans = 0; //计数
while (num != 0 && ++ans >= 0){
num = [ num % 2 == 0 ? num / 2 : num - 1 ] ;
# num=中括号一堆
# 三元运算符A?B:C,通过条件A,执行B,反之C
}
return ans;
}
}