Home > Java > javaTutorial > Number of Steps to Reduce a Number to Zero

Number of Steps to Reduce a Number to Zero

Linda Hamilton
Release: 2024-11-12 11:39:01
Original
698 people have browsed it

Number of Steps to Reduce a Number to Zero

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;
    }
}
Copy after login

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;
    }

}


Copy after login

The above is the detailed content of Number of Steps to Reduce a Number to Zero. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template