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
How to declaring variables in c++?
Explain container class.
Why do we learn c++?
What is the use of cmath in c++?
Can we change the basic meaning of an operator in c++?
What is the difference between interpreters and compilers?
What is the difference between the indirection operator and the address of oper-ator?
write a program that reads in a file and counts the number of lines, words, and characters. Your program should ask the user to input a filename. Open the file and report an error if the file does not exist or cannot be opened for some other reason. Then read in the contents of the file and count the number of lines, words, and characters in the file. Also print additional information about the file, such as the longest and shortest words, and longest and shortest lines. For simplicity, we define a word to be one or more characters ending with white space (a space, tab, carriage return, etc.). Functions for checking the types of characters can be found in the ctype.h header file, so you want to include this header file in your program. For example, the sentence below could be all that is in a file. This sentence IT 104 is taught in C++. has 32 characters, one line, and six words. The shortest line is 32 characters. The longest line is 32 characters. The shortest word is 2 characters. The longest word is 6 characters
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
How many characters are recognized by ANSI C++?
Why struct is used in c++?
How do you initialize a string in c++?
What do the header files usually contains?
What is setw manipulator in c++?
What is the copy-and-swap idiom?