1342. Number of Steps to Reduce a Number to Zero

Mohammad Shariful Islam - Nov 5 - - Dev Community

Problem

https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/

Solution

 class Solution {
    public int numberOfSteps(int num) {
        int steps = 0;
        while (num > 0) {
            if (num % 2 == 0) {
                num /= 2;
                System.out.println(num);

            } else {
                num--;
            }
            steps++;
            System.out.println(steps);

        }
        return steps;
    }
}
Enter fullscreen mode Exit fullscreen mode

Solution 02

class Solution {

    public int numberOfSteps(int num) {
        if (num == 0) {
            return 0;
        } else if (num % 2 == 0) {
            return (numberOfSteps(num / 2) + 1);
        } else if (num % 2 == 1) {
            return (numberOfSteps(num - 1) + 1);
        }
        return 0;
    }

}


Enter fullscreen mode Exit fullscreen mode
. . . . .