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


Please Help Members By Posting Answers For Below Questions

hi to every one .. how to view table pool after creating the pooled table? plz help me.. if any knows abt this ..

1462


Do you know what are bitwise shift operators in c programming?

581


What is 'bus error'?

639


How can I avoid the abort, retry, fail messages?

651


What is pointers in c?

642






explain what are actual arguments?

630


What are the advantages and disadvantages of c language?

556


What are the header files used in c language?

581


What is c language in simple words?

588


what do you mean by enumeration constant?

594


Are pointers really faster than arrays?

556


A variable that is defined in a specified portion of a program but can be used throughout the program a) global variable b) local variable c) character d) none

726


Which is better oop or procedural?

624


What are the standard predefined macros?

627


which of the following is not a character constant a) 'thank you' b) 'enter values of p, n ,r' c) '23.56E-o3' d) all of the above

1410