In: Computer Science
Given the following C function prototype which accepts an integer argument, complete the implementation of the function in C language to return the number of 1’s in the binary representation of the number passed.
For example if the number is (011100011 ) then the function should return 5 as the number of 1s. Please remember that an integer is 32 bits long.
USE the following function int countOnes(int number)
Write a full c program that has the header required and will accept the user entry.
// Please save it as countOnes.c
Thanks
#include<iostream>
using namespace std;
int countOnes(int number)
{
int count=0;
int t = number;
int remainder=0;
while (t != 0)
{
remainder = t % 10; // gets last digit
if(remainder==1) // if last digit is 1
{
count++; // increase count
}
t = t / 10;
// by dividing 10, removes the last digit from number
// 1234/10 gives 123. because t is an integer.
}
return count;
}
int main()
{
int c, num;
printf("\nEnter binary Number (consisting only 1's and
0's): ");
scanf("%d", &num); // get user
input
printf("\nNumber is %d", num);
c = countOnes(num); // get count into
c
printf("\nCount = %d ", c); // display value of
c
}
// -------------------- end of countOnes.c