Number of Steps to Reduce a Number to Zero

Given a non-negative integer num, return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

Example:

Input:  14
Output: 6

Approach

Java

public class StepsReduceToZero {
    public static void main(String[] args) {
        int num = 14;
        int steps = numberOfSteps(num);
        System.out.println(steps);
    }

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

C++

#include <bits/stdc++.h>
using namespace std;

//function to count number of 
//steps to reduce a number to 0
int numberOfSteps (int num
{
    int dp[num+1];
    dp[0]=0;
    dp[1]=1;
    for(int i=2;i<=num;i++)
        {
            if(i&1)
                dp[i]=1+dp[i-1];
            else
                dp[i]=1+dp[i/2];
        }
    return dp[num];
 }
int main()
{
    int n=14;
    cout<<numberOfSteps(n);
    return 0;
}


No comments:

Post a Comment