The language is C, please include comments for eveything done, thank you Reads a
ID: 668683 • Letter: T
Question
The language is C, please include comments for eveything done, thank you
Reads a positive integer n from the input .
Determines the number of ones in the binary representation of n and displays this value.
Requirements:
You may not call any external functions (e.g., from the math library).
Examples:
Supposen=2
The binary representation of 2 is10
So,the program should print something like
That number has1 one(s).
Suppose n=12
The binary representation of 12 is 1100
So, the program should print something like
That number has 2 one(s).
Supposen=31
The binary representation of 31 is 11111
So, the program should print something like
That number has 5 one(s).
Explanation / Answer
#include <stdio.h>
int main( int argc, char *argv[] )
{
int n,count = 0;
printf("Enter a number " );
scanf("%d",&n);
count=0;
while(n!=0){
n = n&(n-1);//n&(n-1) always eliminates the least significant 1
count++;
}
printf("Number of 1's in n is: %d",count);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.