其他分享
首页 > 其他分享> > 力扣 1342. 将数字变成 0 的操作次数

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

作者:互联网

题目来源:https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-to-zero/

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

思路

循环减直至 0

public int numberOfSteps(int num) {
        int ans = 0;
        while (num > 0) {
            num = num % 2 == 0 ? num / 2 : num - 1;
            ans++;
        }
        return ans;
    }

标签:数字,int,1342,number,力扣,次数,num,ans,题意
来源: https://blog.csdn.net/csdn_muxin/article/details/122761227