Leetcode1342. 将数字变成 0 的操作次数

1342. 将数字变成 0 的操作次数

给你一个非负整数 num ,请你返回将它变成 0 所需要的步数。 如果当前数字是偶数,你需要把它除以 2 ;否则,减去 1 。

根据题目要求,对其进行模拟操作即可,在对数据进行操作即可。

可以采用位运算的方式对程序进行一定的优化。

class Solution {
public:
    int numberOfSteps(int num) {
        int ans=0;
        while(num){
            if (num&1) num^=1;
            else num>>=1;
            ans++;
        }
        return ans;
    }
};
posted @ 2021-08-08 17:23  dinghao1262  阅读(63)  评论(0)    收藏  举报