Skip to content
Related Articles

Related Articles

Improve Article

Reduce a number to 1 by performing given operations | Set 2

  • Difficulty Level : Medium
  • Last Updated : 07 Jun, 2021

Given an integer N. The task is to reduce the given number N to 1 in minimum number of given operations. You can perform any one of the below operations in each step. 
 

  1. If the number is even then you can divide the number by 2.
  2. If the number is odd then you are allowed to perform either (N + 1) or (N – 1).

The task is to print the minimum number of steps required to reduce the number N to 1 by performing the above operations.
Examples: 
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: N = 15 
Output:
15 is odd 15 + 1 = 16 
16 is even 16 / 2 = 8 
8 is even 8 / 2 = 4 
4 is even 4 / 2 = 2 
2 is even 2 / 2 = 1
Input: N = 4 
Output:
 



 

Approach: A recursive approach to solve the above problem has already been discussed in this article. In this article, an even optimised approach will be discussed.
The first step towards the solution is to realize that you’re allowed to remove the LSB only if it’s zero i.e. the operation of the first type. Now, what about the odd numbers. One may think that you just need to remove as many 1’s as possible to increase the evenness of the number which is not correct, for example: 
 

111011 -> 111010 -> 11101 -> 11100 -> 1110 -> 111 -> 1000 -> 100 -> 10 -> 1

And yet, this is not the best way because
 

111011 -> 111100 -> 11110 -> 1111 -> 10000 -> 1000 -> 100 -> 10 -> 1

Both 111011 -> 111010 and 111011 -> 111100 remove the same number of 1’s, but the second way is better.
So, maximum number of 1’s have to be removed, doing +1 in case of a tie will fail for the testcase when n = 3 because 11 -> 10 -> 1 is better than 11 -> 100 -> 10 -> 1. Fortunately, that’s the only exception.
So the logic is: 
 

  • If N is even. 
    • Perform the first operation i.e. division by 2.
  • If N is odd. 
    • If N = 3 or (N – 1) has less number of 1’s than (N + 1)
      • Decrement N.
    • else 
      • Increment N.

Below is the implementation of the above approach: 
 

CPP




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the number
// of set bits in n
int set_bits(int n)
{
    int count = 0;
 
    while (n) {
        count += n % 2;
        n /= 2;
    }
 
    return count;
}
 
// Function to return the minimum
// steps required to reach 1
int minSteps(int n)
{
    int ans = 0;
 
    while (n != 1) {
 
        // If n is even then divide it by 2
        if (n % 2 == 0)
            n /= 2;
 
        // If n is 3 or the number of set bits
        // in (n - 1) is less than the number
        // of set bits in (n + 1)
        else if (n == 3
                 or set_bits(n - 1) < set_bits(n + 1))
            n--;
        else
            n++;
 
        // Increment the number of steps
        ans++;
    }
 
    // Return the minimum number of steps
    return ans;
}
 
// Driver code
int main()
{
    int n = 15;
 
    cout << minSteps(n);
 
    return 0;
}

Java




// Java implementation of the approach
class GFG
{
 
// Function to return the number
// of set bits in n
static int set_bits(int n)
{
    int count = 0;
 
    while (n > 0)
    {
        count += n % 2;
        n /= 2;
    }
    return count;
}
 
// Function to return the minimum
// steps required to reach 1
static int minSteps(int n)
{
    int ans = 0;
 
    while (n != 1)
    {
 
        // If n is even then divide it by 2
        if (n % 2 == 0)
            n /= 2;
 
        // If n is 3 or the number of set bits
        // in (n - 1) is less than the number
        // of set bits in (n + 1)
        else if (n == 3
                || set_bits(n - 1) < set_bits(n + 1))
            n--;
        else
            n++;
 
        // Increment the number of steps
        ans++;
    }
 
    // Return the minimum number of steps
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int n = 15;
 
    System.out.print(minSteps(n));
}
}
 
// This code is contributed by PrinciRaj1992

Python




# Python3 implementation of the approach
 
# Function to return the number
# of set bits in n
def set_bits(n):
    count = 0
 
    while (n):
        count += n % 2
        n //= 2
 
    return count
 
# Function to return the minimum
# steps required to reach 1
def minSteps(n):
    ans = 0
 
    while (n != 1):
 
        # If n is even then divide it by 2
        if (n % 2 == 0):
            n //= 2
 
        # If n is 3 or the number of set bits
        # in (n - 1) is less than the number
        # of set bits in (n + 1)
        elif (n == 3 or set_bits(n - 1) < set_bits(n + 1)):
            n -= 1
        else:
            n += 1
 
        # Increment the number of steps
        ans += 1
 
    # Return the minimum number of steps
    return ans
 
# Driver code
n = 15
 
print(minSteps(n))
 
# This code is contributed by mohit kumar 29

C#




// C# implementation of the approach
using System;
 
class GFG
{
 
// Function to return the number
// of set bits in n
static int set_bits(int n)
{
    int count = 0;
 
    while (n > 0)
    {
        count += n % 2;
        n /= 2;
    }
    return count;
}
 
// Function to return the minimum
// steps required to reach 1
static int minSteps(int n)
{
    int ans = 0;
 
    while (n != 1)
    {
 
        // If n is even then divide it by 2
        if (n % 2 == 0)
            n /= 2;
 
        // If n is 3 or the number of set bits
        // in (n - 1) is less than the number
        // of set bits in (n + 1)
        else if (n == 3
                || set_bits(n - 1) < set_bits(n + 1))
            n--;
        else
            n++;
 
        // Increment the number of steps
        ans++;
    }
 
    // Return the minimum number of steps
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 15;
 
    Console.Write(minSteps(n));
}
}
 
// This code is contributed by Rajput-Ji

Javascript




<script>
 
// JavaScript implementation of the approach
 
// Function to return the number
// of set bits in n
function set_bits(n)
{
    let count = 0;
 
    while (n) {
        count += n % 2;
        n = parseInt(n / 2);
    }
 
    return count;
}
 
// Function to return the minimum
// steps required to reach 1
function minSteps(n)
{
    let ans = 0;
 
    while (n != 1) {
 
        // If n is even then divide it by 2
        if (n % 2 == 0)
            n = parseInt(n / 2);
 
        // If n is 3 or the number of set bits
        // in (n - 1) is less than the number
        // of set bits in (n + 1)
        else if (n == 3
                 || set_bits(n - 1) < set_bits(n + 1))
            n--;
        else
            n++;
 
        // Increment the number of steps
        ans++;
    }
 
    // Return the minimum number of steps
    return ans;
}
 
// Driver code
    let n = 15;
 
    document.write(minSteps(n));
 
</script>
Output: 
5

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :