Given an integer N, the task is to find the minimum number of coins of the form 2i required to make a change for N cents.
Examples:
Input: N = 5
Output: 2
Explanation:
Possible values of coins are: {1, 2, 4, 8, …}
Possible ways to make change for N cents are as follows:
5 = 1 + 1 + 1 + 1 + 1
5 = 1 + 2 + 2
5 = 1 + 4 (Minimum)
Therefore, the required output is 2
Input: N = 4
Output: 4
Naive Approach: The simplest approach to solve this problem is to store all possible values of the coins in an array and print the minimum count of coins required to make a change for N cents using Dynamic programming.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized using the fact that any number can be represented in the form of a power of 2s. The idea is to count the set bits of N and print the count obtained. Follow the steps below to solve the problem:
- Iterate over the bits in the binary representation of N and check if the current bit is set or not. If found to be true, then increment the count.
- Finally, print the total count obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void count_setbit( int N)
{
int result = 0;
for ( int i = 0; i < 32; i++) {
if ((1 << i) & N) {
result++;
}
}
cout << result << endl;
}
int main()
{
int N = 43;
count_setbit(N);
return 0;
}
|
C
#include <stdio.h>
void count_setbit( int N)
{
int result = 0;
for ( int i = 0; i < 32; i++) {
if ((1 << i) & N) {
result++;
}
}
printf ( "%d\n" , result);
}
int main()
{
int N = 43;
count_setbit(N);
return 0;
}
|
Java
public class Main {
public static void count_setbit( int N)
{
int result = 0 ;
for ( int i = 0 ; i < 32 ; i++) {
if ((( 1 << i) & N) > 0 ) {
result++;
}
}
System.out.println(result);
}
public static void main(String[] args)
{
int N = 43 ;
count_setbit(N);
}
}
|
Python
def count_setbit(N):
result = 0
for i in range ( 32 ):
if ( ( 1 << i) & N ):
result = result + 1
print (result)
if __name__ = = '__main__' :
N = 43
count_setbit(N)
|
C#
using System;
class GFG {
static void count_setbit( int N)
{
int result = 0;
for ( int i = 0; i < 32; i++) {
if (((1 << i) & N) > 0) {
result++;
}
}
Console.WriteLine(result);
}
static void Main()
{
int N = 43;
count_setbit(N);
}
}
|
Javascript
<script>
function count_setbit(N)
{
let result = 0;
for (let i = 0; i < 32; i++) {
if (((1 << i) & N) > 0) {
result++;
}
}
document.write(result);
}
let N = 43;
count_setbit(N);
</script>
|
Time Complexity: O(log2(N))
Auxiliary Space: O(1)