📌  相关文章
📜  最小化将 N 减少到 0 所需的给定翻转

📅  最后修改于: 2021-09-22 09:45:13             🧑  作者: Mango

给定一个整数N ,任务是通过执行以下操作的最少次数将N的值减少到0

  • 翻转N的二进制表示中最右边(0)的位。
  • 如果(I – 1)被设置,然后翻转第i位和选自(i – 2)清除所有位到0比特。

例子:

方法:该问题可以基于以下观察来解决:

请按照以下步骤解决问题:

  • 使用log 2 (N) + 1计算N 的二进制表示中的位数。
  • 使用上述递推关系并计算将N减少到0所需的最小操作数。

下面是上述方法的实现。

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to find the minimum count of
// operations required to Reduce N to 0
int MinOp(int N)
{
 
    if (N <= 1)
        return N;
 
    // Stores count of
    // bits in N
    int bit = log2(N) + 1;
 
    // Recurrence relation
    return ((1 << bit) - 1)
           - MinOp(N - (1 << (bit - 1)));
}
 
// Driver Code
int main()
{
 
    int N = 4;
    cout << MinOp(N);
    return 0;
}


Java
// Java program to implement
// the above approach
class GFG{
     
// Function to find the minimum count of
// operations required to Reduce N to 0
public static int MinOp(int N)
{
    if (N <= 1)
        return N;
   
    // Stores count of
    // bits in N
    int bit = (int)(Math.log(N) /
                    Math.log(2)) + 1;
   
    // Recurrence relation
    return ((1 << bit) - 1) - MinOp(
        N - (1 << (bit - 1)));
}
 
// Driver code
public static void main(String[] args)
{
    int N = 4;
     
    System.out.println(MinOp(N));
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python program to implement
# the above approach
 
# Function to find the minimum count of
# operations required to Reduce N to 0
import math
def MinOp(N):
    if (N <= 1):
        return N;
 
    # Stores count of
    # bits in N
    bit = (int)(math.log(N) / math.log(2)) + 1;
 
    # Recurrence relation
    return ((1 << bit) - 1) - MinOp(N - (1 << (bit - 1)));
 
# Driver code
if __name__ == '__main__':
    N = 4;
 
    print(MinOp(N));
 
# This code is contributed by 29AjayKumar


C#
// C# program to implement
// the above approach 
using System;
 
class GFG{
     
// Function to find the minimum count of
// operations required to Reduce N to 0
public static int MinOp(int N)
{
    if (N <= 1)
        return N;
         
    // Stores count of
    // bits in N
    int bit = (int)(Math.Log(N) /
                    Math.Log(2)) + 1;
                     
    // Recurrence relation
    return ((1 << bit) - 1) - MinOp(
        N - (1 << (bit - 1)));
}
  
// Driver code
public static void Main()
{
    int N = 4;
     
    Console.WriteLine(MinOp(N));
}
}
 
// This code is contributed by sanjoy_62


Javascript


输出:
7

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程