Give a very good method to count the number of ones in a "n"
(e.g. 32) bit number.

Answer Posted / sujan

#include<iostream>
#define bit 32
using namespace std;

int array[bit];

int bitConvert(int n)
{
int a,j=0;

a=n%2;
for(int i=bit;i>=0;i--)
{
n=n/2;
array[i]=a;
a=n%2;
}
for(int i=0;i<=bit;i++)
{
cout<<array[i];

}
}
int countBit(int a[])
{
int *ptr;
ptr=a;
int j=0;
for(int i=0;i<=bit;i++)
{

if(*ptr==1)
{
j++;
}
ptr++;
}
cout<< j;
}

int main()
{
int n;
cout<<"Enter the no:";
cin>>n;
cout<<"\n"<<"BitConversion of "<<n<< "is:";
bitConvert(n);
cout<<endl<<endl;
cout<<"\n"<<"No. of bit:";
countBit(array);
system("pause");
}

Is This Answer Correct ?    4 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why can templates only be implemented in the header file?

648


What is problem with overriding functions?

599


Which is most difficult programming language?

571


Is C++ case sensitive a) False b) Depends on implementation c) True

608


What is difference between c++ 11 and c++ 14?

565






Explain linear search.

617


What is c++ stringstream?

592


What are virtual constructors/destructors?

567


What do the header files usually contains?

618


What is friend class in c++ with example?

492


Write a Program for read a line from file from location N1 to N2 using command line arguments. Eg:exe 10 20 a.c

785


What is lambda in c++?

568


What is conditions when using boolean operators?

590


What are literals in C++?

583


What is #include iostream?

727