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

What is scope rule in c?

609


How can a process change an environment variable in its caller?

658


Explain bitwise shift operators?

636


How many header files are in c?

560


How do I get an accurate error status return from system on ms-dos?

653






How can I send mail from within a c program?

589


In this assignment you are asked to write a multithreaded program to find the duplicates in an array of 10 million integers. The integers are between -5000,000 to 5000,000 and are generated randomly. Use 10 threads, each thread works on 1000,000 integers. Compare the time needed to accomplish the task with single thread of execution program. Do not include the time to fill the array with integers in the execution time.

2688


The performance of an operation in several steps with each step using the output of the preceding step a) recursion b) search c) call by value d) call by reference

679


What are identifiers in c?

640


Tell me can the size of an array be declared at runtime?

603


how to capitalise first letter of each word in a given string?

1436


Why void is used in c?

571


Are pointers integer?

555


Define Array of pointers.

638


In c programming typeing to occupy the variables in memory space. if not useing the variable the memory space is wasted.ok, how to avoid the situation..? (the variable is used & notused)

1637