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

Answers were Sorted based on User's Feedback



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

Answer / 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

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

Answer / artyom

// It's still O(n), maybe there are better ways.
int countBit(int num)
{
int count = 0;
while(num)
{
count += static_cast<int>(static_cast<bool>(mask &
0x1));
num >>= 1;
}
return count;
}

Is This Answer Correct ?    2 Yes 0 No

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

Answer / manish kumar

for (c = 0; n; c++)
n &= n - 1;

Result: the value of c.

complexity:o(logn)

Is This Answer Correct ?    1 Yes 0 No

Post New Answer

More C++ General Interview Questions

What is a list c++?

0 Answers  


What is the difference between static global and global ?

2 Answers   CA,


write the prime no program in c++?

16 Answers  


How to access a variable of the structure?

0 Answers  


What is the output of: String a1 = "Hello"; String a2 = "world!"; String* s1 = &a2; String& s2 = a1; s1 = &a1; s2 = a2; std::cout << *s1 << " " << s2 << std::endl;

4 Answers   Lehman Brothers,






Discussion on error handling of C++ .

0 Answers  


What is your strongest programming language (Java, ASP, C, C++, VB, HTML,C#, etc.)?

24 Answers   Infosys, Microsoft, TCS,


What is a static member?

0 Answers  


class base { public: int fun(int) {} }; class base2 { public: int fun(float) { } }; so here qustion is both function either function overloading or over riding;

4 Answers   Manhattan,


What is a vector c++?

0 Answers  


What is the use of 'using' declaration in c++?

0 Answers  


Is main a class in c++?

0 Answers  


Categories