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
pgm to find number of words starting with capital letters in a file(additional memory usage not allowed)(if a word starting with capital also next letter in word is capital cann't be counted twice)
What is the code in while loop that returns the output of given code?
shorting algorithmS
all c language question
What is string length in c?
What does the message "automatic aggregate intialization is an ansi feature" mean?
i have a written test for microland please give me test pattern
How many types of arrays are there in c?
What is nested structure in c?
How is null defined in c?
How many types of operator or there in c?
#define f(g,h) g##h main O int i=0 int var=100 ; print f ("%d"f(var,10));} wat would be the output??
How can I make sure that my program is the only one accessing a file?
what is stack , heap ,code segment,and data segment
In a byte, what is the maximum decimal number that you can accommodate?