how do u find out the number of 1's in the binary
representation of a decimal number without converting it
into binary(i mean without dividing by 2 and finding out
the remainder)? three lines of c code s there it
seems...can anyone help
Answer Posted / krishna
The above solutions will not work for negative numbers.
if a negative number is right shifted, the most significant bit will become 1. so the number never becomes zero.
The following will work for both +ve and -ve numbers.
#include <stdio.h>
int main(int argc, char *argv[]) {
int count = 0;
int no = 3;
int x = 0x01;
if ( argc > 1) {
no = atoi(argv[1]);
}
while ( x != 0) {
if( no & x ) {
count++;
}
x <<= 1;
}
printf( "number: %d , no.of 1s in it: %d\n", no, count);
return 0;
}
| Is This Answer Correct ? | 1 Yes | 2 No |
Post New Answer View All Answers
What are operators in c?
What is a null string in c?
Which node is more powerful and can handle local information processing or graphics processing?
to find the closest pair
What is the purpose of void in c?
Are the outer parentheses in return statements really optional?
Why is void main used?
Can variables be declared anywhere in c?
Why isnt any of this standardized in c?
Explain how do you determine whether to use a stream function or a low-level function?
What is pointer and structure in c?
Can a file other than a .h file be included with #include?
Can an array be an Ivalue?
How do c compilers work?
Can a void pointer point to a function?