题目地址:
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/description/?envType=company&envId=hrt&favoriteSlug=hrt-all
给定一个正整数
n
n
n,如果是偶数则除以
2
2
2,否则减
1
1
1,问多少步能到
0
0
0。
代码如下:
class Solution {
public:
int numberOfSteps(int num) {
int res = 0;
while (num) {
if (num & 1)
num--;
else
num /= 2;
res++;
}
return res;
}
};
时间复杂度
O
(
log
n
)
O(\log n)
O(logn),空间
O
(
1
)
O(1)
O(1)。