1342. Number of Steps to Reduce a Number to Zero

1342. Number of Steps to Reduce a Number to Zero

Question

Given an integer num, return the number of steps to reduce it to zero.

In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

Solution

循环,当num不等于零时,如果为奇数则减一,如果为偶数则除以2。
每次循环记录次数。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int numberOfSteps(int num) {
int count =0;
while(num != 0){
count++;
if((num & 1) == 0){
num/=2;
}
else{
num--;
}
}
return count;
}
}
Author

Xander

Posted on

2022-05-27

Updated on

2022-05-27

Licensed under

Comments