通过加 1 或乘以 2 以最小步长将 0 转换为 N
给定一个正整数N ,任务是找到将数字0转换为N所需的最小加法运算次数,以便在每个运算中任何数字都可以乘以 2或将值加 1 。
例子:
Input: N = 6
Output: 1
Explanation:
Following are the operations performed to convert 0 to 6:
Add 1 –> 0 + 1 = 1.
Multiply 2 –> 1 * 2 = 2.
Add 1 –> 2 + 1 = 3.
Multiply 2 –> 3 * 2 = 6.
Therefore number of addition operations = 2.
Input: N = 3
Output: 2
方法:这个问题可以通过使用位操作技术来解决。在N的二进制数表示中,当N变为奇数时(这意味着设置了N的最低有效位)对每个位进行运算,然后执行加法运算。否则,乘以 2 。给定问题的最终逻辑是找到 N 中设置的位数。
下面是上述方法的实现:
C++
// C++ program for above approach
#include
using namespace std;
// Function to count number of
// set bits in N
int minimumAdditionOperation(
unsigned long long int N)
{
// Stores the count of set bits
int count = 0;
while (N) {
// If N is odd, then it
// a set bit
if (N & 1 == 1) {
count++;
}
N = N >> 1;
}
// Return the result
return count;
}
// Driver Code
int main()
{
int N = 6;
cout << minimumAdditionOperation(N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG {
// Function to count number of
// set bits in N
static int minimumAdditionOperation(int N)
{
// Stores the count of set bits
int count = 0;
while (N > 0) {
// If N is odd, then it
// a set bit
if (N % 2 == 1) {
count++;
}
N = N >> 1;
}
// Return the result
return count;
}
// Driver Code
public static void main(String[] args)
{
int N = 6;
System.out.println(minimumAdditionOperation(N));
}
}
// This code is contributed by dwivediyash
Python3
# python program for above approach
# Function to count number of
# set bits in N
def minimumAdditionOperation(N):
# Stores the count of set bits
count = 0
while (N):
# If N is odd, then it
# a set bit
if (N & 1 == 1):
count += 1
N = N >> 1
# Return the result
return count
# Driver Code
if __name__ == "__main__":
N = 6
print(minimumAdditionOperation(N))
# This code is contributed by rakeshsahni.
C#
// C# program for above approach
using System;
public class GFG{
// Function to count number of
// set bits in N
static int minimumAdditionOperation(int N)
{
// Stores the count of set bits
int count = 0;
while (N != 0) {
// If N is odd, then it
// a set bit
if ((N & 1) == 1) {
count++;
}
N = N >> 1;
}
// Return the result
return count;
}
// Driver Code
static public void Main (){
int N = 6;
Console.Write(minimumAdditionOperation(N));
}
}
// This code is contributed by AnkThon
Javascript
输出:
2
时间复杂度: O(log N)
辅助空间: O(1)