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...

#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...

// It's still O(n), maybe there are better ways.
int countBit(int num)
{
int count = 0;
while(num)
{
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...

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

Result: the value of c.

complexity:o(logn)

 Is This Answer Correct ? 1 Yes 0 No

More C++ General Interview Questions

When is a template better solution than a base class??

Write a program that takes a 5 digit number and calculates 2 power that number and prints it.

What compiler was used?

How many lines of code you have written for a single program?

How to write a program such that it will delete itself after exectution?

i have given a project to create examination seating plan system in c++. so can anyone send me the answer of this question quickly??????

a class that maintains a pointer to an object that is programatically accessible through the public interface is known as?

I want to write a C++ language program that: 1. Reads in the size of a square from the screen; 2. Prints a hollow square of that size out of “-“, “|” and blanks on screen; 3. Prints the same hollow square onto a text file. The program should work for squares of all side sizes between 1 and 20.

What is RTRT tool?can it be used for automation?can it work on packet PC?

I want explanation for this assignment: how to connect mysql database using c/c++,please explain this detailly?

How the memory management in vectors are being done. What happens when the heap memory is full, and how do you handle it ?

Given a simple program designed to take inputs of integers from 1-1000 and to output the factorial value of that number, how would you test this program? You do not have access to the code. Please be as specific as possible.

Categories