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

Devise a program that inputs a 3 digit number n and finds out whether the number is prime or not. Find out its factors.

676


What is register variable in c language?

612


What is the difference between ā€˜gā€™ and ā€œgā€ in C?

2705


What are local static variables? How can you use them?

653


Why do we use namespace feature?

590






How do you define a function?

595


What are logical errors and how does it differ from syntax errors?

672


What are reserved words?

664


Explain what is wrong with this program statement?

634


What is a class c rental property?

626


How do I get a null pointer in my programs?

636


How many levels of indirection in pointers can you have in a single declaration?

605


What is array in c with example?

627


What is the use of volatile?

618


What is the importance of c in your views?

603