[LeetCode] Number of Steps to Reduce a Number to Zero

1342. Number of Steps to Reduce a Number to Zero

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.

1
2
3
4
5
6
class Solution {
public:
int numberOfSteps(int num) {
return num == 0 ? 0 : log2(num) + __builtin_popcount(num);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/27/PS/LeetCode/number-of-steps-to-reduce-a-number-to-zero/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.