📌  相关文章
📜  通过执行给定的操作将数字减为 1 |设置 3

📅  最后修改于: 2022-05-13 01:56:06.738000             🧑  作者: Mango

通过执行给定的操作将数字减为 1 |设置 3

给定一个整数N ,任务是通过执行以下操作找到将给定数字N减少到1所需的步骤数:

  1. 如果该数字是 2 的幂,则将该数字除以2
  2. 否则,从N中减去小于N的 2 的最大幂。

例子:

方法 1 –

方法:这个想法是递归地计算所需的最小步骤数。

  • 如果这个数字是 2 的幂,那么我们只能将这个数字除以2
  • 否则,我们可以从N中减去小于 N 的 2 的最大幂。
  • 因此,我们将对有效的操作和返回的操作数使用递归。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Utility function to check
// if n is power of 2
int highestPowerof2(int n)
{
   int p = (int)log2(n);
   return (int)pow(2, p);
}
 
// Utility function to find highest
// power of 2 less than or equal
// to given number
bool isPowerOfTwo(int n)
{
   if(n==0)
   return false;
   
   return (ceil(log2(n)) == floor(log2(n)));
}
 
// Recursive function to find
// steps needed to reduce
// a given integer to 1
int reduceToOne(int N)
{
    // Base Condition
    if(N == 1){
        return 0;
    }
    // If the number is a power of 2
    if(isPowerOfTwo(N) == true){
        return 1 + reduceToOne(N/2);
    }
    // Else subtract the greatest
    //power of 2 smaller than N
    //from N
    else{
        return 1 + reduceToOne(N - highestPowerof2(N));
    }
}
 
// Driver Code
int main()
{
    // Input
    int N = 7;
    // Function call
    cout << reduceToOne(N) << endl;
}


Java
// java program for the above approach
 
class GFG {
   
  // Utility function to check
  // if n is power of 2
  static int highestPowerof2(int n)
  {
     int p = (int)(Math.log(n) / Math.log(2));
     return (int)Math.pow(2, p);
  }
 
  // Utility function to find highest
  // power of 2 less than or equal
  // to given number
  static boolean isPowerOfTwo(int n)
  {
     if(n==0)
     return false;
 
     return (int)(Math.ceil((Math.log(n) / Math.log(2)))) ==
       (int)(Math.floor(((Math.log(n) / Math.log(2)))));
  }
 
  // Recursive function to find
  // steps needed to reduce
  // a given integer to 1
  static int reduceToOne(int N)
  {
      // Base Condition
      if(N == 1){
          return 0;
      }
      // If the number is a power of 2
      if(isPowerOfTwo(N) == true){
          return 1 + reduceToOne(N/2);
      }
      // Else subtract the greatest
      //power of 2 smaller than N
      //from N
      else{
          return 1 + reduceToOne(N - highestPowerof2(N));
      }
  }
 
  // Driver Code
  public static void main(String [] args)
  {
      // Input
      int N = 7;
      // Function call
      System.out.println(reduceToOne(N));
  }
   
}
 
 
// This code is contributed by ihritik


Python
# Python program for the above approach
import math
 
# Utility function to check
# Log base 2
def Log2(x):
    if x == 0:
        return false;
  
    return (math.log10(x) /
            math.log10(2));
  
# Utility function to check
# if x is power of 2
def isPowerOfTwo(n):
    return (math.ceil(Log2(n)) ==
            math.floor(Log2(n)));
 
# Utility function to find highest
# power of 2 less than or equal
# to given number
def highestPowerof2(n):
  
    p = int(math.log(n, 2));
    return int(pow(2, p));
 
# Recursive function to find
# steps needed to reduce
# a given integer to 1
def reduceToOne(N):
     
    # Base Condition
    if(N == 1):
        return 0
         
    # If the number is a power of 2
    if(isPowerOfTwo(N) == True):
        return 1 + reduceToOne(N/2)
         
    # Else subtract the greatest
    # power of 2 smaller than N
    # from N
    else:
        return 1 + reduceToOne(N - highestPowerof2(N))
 
# Driver Code
 
# Input
N = 7;
 
#Function call
print(reduceToOne(N))
 
# This code is contributed by Samim Hossain Mondal.


C#
// C# program for the above approach
using System;
 
class GFG {
   
  // Utility function to check
  // if n is power of 2
  static int highestPowerof2(int n)
  {
     int p = (int)(Math.Log(n) / Math.Log(2));
     return (int)Math.Pow(2, p);
  }
 
  // Utility function to find highest
  // power of 2 less than or equal
  // to given number
  static bool isPowerOfTwo(int n)
  {
     if(n == 0)
     return false;
 
     return (int)(Math.Ceiling((Math.Log(n) / Math.Log(2)))) ==
       (int)(Math.Floor(((Math.Log(n) / Math.Log(2)))));
  }
 
  // Recursive function to find
  // steps needed to reduce
  // a given integer to 1
  static int reduceToOne(int N)
  {
     
      // Base Condition
      if(N == 1){
          return 0;
      }
     
      // If the number is a power of 2
      if(isPowerOfTwo(N) == true){
          return 1 + reduceToOne(N/2);
      }
     
      // Else subtract the greatest
      //power of 2 smaller than N
      //from N
      else{
          return 1 + reduceToOne(N - highestPowerof2(N));
      }
  }
 
  // Driver Code
  public static void Main()
  {
     
      // Input
      int N = 7;
     
      // Function call
      Console.Write(reduceToOne(N));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find steps needed to
// reduce a given integer to 1
int reduceToOne(int N)
{
    // Stores the most
    // significant bit of N
    int MSB = log2(N);
 
    // Stores the number of steps
    // required to reduce N to 1
    int res = 0;
 
    // Iterates while N
    // is not equal 1
    while (N != 1) {
 
        // Increment res by 1
        res++;
 
        // If N is power of 2
        if (N & (N - 1) == 0) {
 
            // Divide N by 2
            N /= 2;
        }
        // Otherwise
        else {
 
            // Subtract 2 ^ MSB
            // from N
            N -= (1 << MSB);
        }
        // Decrement MSB by 1
        MSB--;
    }
    // Returns res
    return res;
}
 
// Driver code
int main()
{
    // Input
    int N = 7;
    // Function call
    cout << reduceToOne(N) << endl;
}


Java
/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
    public static int logarithm(int number, int base)
    {
        int res = (int)(Math.log(number) / Math.log(base));
        return res;
    }
    public static int reduceToOne(int N)
    {
       
        // Stores the most
        // significant bit of N
        int MSB = logarithm(N, 2);
 
        // Stores the number of steps
        // required to reduce N to 1
        int res = 0;
 
        // Iterates while N
        // is not equal 1
        while (N != 1) {
 
            // Increment res by 1
            res++;
 
            // If N is power of 2
            if ((N & (N - 1)) == 0) {
 
                // Divide N by 2
                N /= 2;
            }
            // Otherwise
            else {
 
                // Subtract 2 ^ MSB
                // from N
                N -= (1 << MSB);
            }
            // Decrement MSB by 1
            MSB--;
        }
        // Returns res
        return res;
    }
 
    public static void main(String[] args)
    {
        int N = 7;
        int res = reduceToOne(N);
        System.out.println(res);
    }
}
 
// This code is contributed by lokeshpotta20.


Python3
# Python program for the above approach
import math
 
# Function to find steps needed to
# reduce a given integer to 1
def reduceToOne(N):
     
    # Stores the most
    # significant bit of N
    MSB = math.floor(math.log2(N))
     
    # Stores the number of steps
    # required to reduce N to 1
    res = 0
     
    # Iterates while N
    # is not equal 1
    while (N != 1):
         
        # Increment res by 1
        res += 1
         
        # If N is power of 2
        if (N & (N - 1) == 0):
             
            # Divide N by 2
            N //= 2
         
        # Otherwise
        else:
            # Subtract 2 ^ MSB
            # from N
            N -= (1 << MSB)
             
        # Decrement MSB by 1
        MSB-=1
     
    # Returns res
    return res
     
# Driver code
# Input
N = 7
# Function call
print(reduceToOne(N))
 
# This code is contributed by shubham Singh


C#
// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find steps needed to
// reduce a given integer to 1
static int reduceToOne(int N)
{
   
    // Stores the most
    // significant bit of N
    int MSB = (int)(Math.Log(N)/Math.Log(2));
 
    // Stores the number of steps
    // required to reduce N to 1
    int res = 0;
 
    // Iterates while N
    // is not equal 1
    while (N != 1) {
 
        // Increment res by 1
        res++;
 
        // If N is power of 2
        if ((N & (N - 1)) == 0) {
 
            // Divide N by 2
            N /= 2;
        }
        // Otherwise
        else {
 
            // Subtract 2 ^ MSB
            // from N
            N -= (1 << MSB);
        }
       
        // Decrement MSB by 1
        MSB--;
    }
   
    // Returns res
    return res;
}
 
// Driver code
public static void Main()
{
    // Input
    int N = 7;
   
    // Function call
    Console.Write(reduceToOne(N));
}
}
 
// This code is contributed by bgangwar59.


Javascript


输出
2

方法 2 –

方法:给定的问题可以使用按位运算运算符来解决。请按照以下步骤解决问题:

  • 初始化两个变量res值为0MSB值为log 2 (N)以存储将数字减少到1所需的步数和N的最高有效位。
  • N不等于1 时迭代:
    • 检查数字是否是 2 的幂,然后将N除以2
    • 否则,从N中减去小于 N 的 2 的最大幂,即将N更新为N=N-2 MSB
    • res增加1并将MSB减少1
  • 最后,打印res

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to find steps needed to
// reduce a given integer to 1
int reduceToOne(int N)
{
    // Stores the most
    // significant bit of N
    int MSB = log2(N);
 
    // Stores the number of steps
    // required to reduce N to 1
    int res = 0;
 
    // Iterates while N
    // is not equal 1
    while (N != 1) {
 
        // Increment res by 1
        res++;
 
        // If N is power of 2
        if (N & (N - 1) == 0) {
 
            // Divide N by 2
            N /= 2;
        }
        // Otherwise
        else {
 
            // Subtract 2 ^ MSB
            // from N
            N -= (1 << MSB);
        }
        // Decrement MSB by 1
        MSB--;
    }
    // Returns res
    return res;
}
 
// Driver code
int main()
{
    // Input
    int N = 7;
    // Function call
    cout << reduceToOne(N) << endl;
}

Java

/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
    public static int logarithm(int number, int base)
    {
        int res = (int)(Math.log(number) / Math.log(base));
        return res;
    }
    public static int reduceToOne(int N)
    {
       
        // Stores the most
        // significant bit of N
        int MSB = logarithm(N, 2);
 
        // Stores the number of steps
        // required to reduce N to 1
        int res = 0;
 
        // Iterates while N
        // is not equal 1
        while (N != 1) {
 
            // Increment res by 1
            res++;
 
            // If N is power of 2
            if ((N & (N - 1)) == 0) {
 
                // Divide N by 2
                N /= 2;
            }
            // Otherwise
            else {
 
                // Subtract 2 ^ MSB
                // from N
                N -= (1 << MSB);
            }
            // Decrement MSB by 1
            MSB--;
        }
        // Returns res
        return res;
    }
 
    public static void main(String[] args)
    {
        int N = 7;
        int res = reduceToOne(N);
        System.out.println(res);
    }
}
 
// This code is contributed by lokeshpotta20.

Python3

# Python program for the above approach
import math
 
# Function to find steps needed to
# reduce a given integer to 1
def reduceToOne(N):
     
    # Stores the most
    # significant bit of N
    MSB = math.floor(math.log2(N))
     
    # Stores the number of steps
    # required to reduce N to 1
    res = 0
     
    # Iterates while N
    # is not equal 1
    while (N != 1):
         
        # Increment res by 1
        res += 1
         
        # If N is power of 2
        if (N & (N - 1) == 0):
             
            # Divide N by 2
            N //= 2
         
        # Otherwise
        else:
            # Subtract 2 ^ MSB
            # from N
            N -= (1 << MSB)
             
        # Decrement MSB by 1
        MSB-=1
     
    # Returns res
    return res
     
# Driver code
# Input
N = 7
# Function call
print(reduceToOne(N))
 
# This code is contributed by shubham Singh

C#

// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find steps needed to
// reduce a given integer to 1
static int reduceToOne(int N)
{
   
    // Stores the most
    // significant bit of N
    int MSB = (int)(Math.Log(N)/Math.Log(2));
 
    // Stores the number of steps
    // required to reduce N to 1
    int res = 0;
 
    // Iterates while N
    // is not equal 1
    while (N != 1) {
 
        // Increment res by 1
        res++;
 
        // If N is power of 2
        if ((N & (N - 1)) == 0) {
 
            // Divide N by 2
            N /= 2;
        }
        // Otherwise
        else {
 
            // Subtract 2 ^ MSB
            // from N
            N -= (1 << MSB);
        }
       
        // Decrement MSB by 1
        MSB--;
    }
   
    // Returns res
    return res;
}
 
// Driver code
public static void Main()
{
    // Input
    int N = 7;
   
    // Function call
    Console.Write(reduceToOne(N));
}
}
 
// This code is contributed by bgangwar59.

Javascript


输出
2

时间复杂度: O(log(N))
辅助空间: O(1)