In: Computer Science
/*
* bitCount - returns count of number of 1's in word
* Examples: bitCount(5) = 2, bitCount(7) = 3
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 40
* Rating: 4
*/
int bitCount(int x) {
return 2;
}
Can you please complete this code in C language without the use of any loops such as if, do, while, for, switch, etc., macros, other operations, such as &&, ||, -, or ?: .
//C Code
#include <math.h>
#include <stdio.h>
// Recursive approach to find the
// number of set bit in 1
int recursiveCount(int N)
{
// Base Case
if (N == 0) {
return 0;
}
// Return recursively
return (N & 1) + recursiveCount(N >> 1);
}
// Function to find 1s complement
int onesComplement(int n)
{
// Find number of bits in the
// given integer
int N = floor(log2(n)) + 1;
// XOR the given integer with
// pow(2, N) - 1
return ((1 << N) - 1) ^ n;
}
// Function to count the number of
// 1s in binary representation of N
void bitCount(int N)
{
// Initialise the count variables
int count1;
// Function call to find the number
// of set bits in N
count1 = recursiveCount(N);
// Function call to find 1s complement
N = onesComplement(N);
// Print the count
printf("Count of 1s is %d\n", count1);
}
// Driver Code
int main()
{
int N=7;
// Function Call
bitCount(N);
return 0;
}
Code Snapshot:
Output Snapshot: