Convert 0 to N by adding 1 or multiplying by 2 in minimum steps
Given a positive integer N, the task is to find the minimum number of addition operations required to convert the number 0 to N such that in each operation any number can be multiplied by 2 or add the value 1 to it.
Examples:
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
Approach: This problem can be solved by using the Bit Manipulation technique. In binary number representation of N, while operating each bit whenever N becomes odd (that means the least significant bit of N is set) then perform the addition operation. Otherwise, multiply by 2. The final logic to the given problem is to find the number of set bits in N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumAdditionOperation(
unsigned long long int N)
{
int count = 0;
while (N) {
if (N & 1 == 1) {
count++;
}
N = N >> 1;
}
return count;
}
int main()
{
int N = 6;
cout << minimumAdditionOperation(N);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int minimumAdditionOperation( int N)
{
int count = 0 ;
while (N > 0 ) {
if (N % 2 == 1 ) {
count++;
}
N = N >> 1 ;
}
return count;
}
public static void main(String[] args)
{
int N = 6 ;
System.out.println(minimumAdditionOperation(N));
}
}
|
Python3
def minimumAdditionOperation(N):
count = 0
while (N):
if (N & 1 = = 1 ):
count + = 1
N = N >> 1
return count
if __name__ = = "__main__" :
N = 6
print (minimumAdditionOperation(N))
|
C#
using System;
public class GFG{
static int minimumAdditionOperation( int N)
{
int count = 0;
while (N != 0) {
if ((N & 1) == 1) {
count++;
}
N = N >> 1;
}
return count;
}
static public void Main (){
int N = 6;
Console.Write(minimumAdditionOperation(N));
}
}
|
Javascript
<script>
function minimumAdditionOperation(N)
{
let count = 0;
while (N)
{
if (N & (1 == 1)) {
count++;
}
N = N >> 1;
}
return count;
}
let N = 6;
document.write(minimumAdditionOperation(N));
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(1)
Last Updated :
03 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...