Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

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 the g value paradox?

1126


Explain the process of converting a Tree into a Binary Tree.

2633


What is calloc()?

1046


What are linked lists in c?

1104


What are the 5 organizational structures?

995


What are identifiers c?

1037


For what purpose null pointer used?

1034


How does #define work?

1036


Is it possible to use curly brackets ({}) to enclose single line code in c program?

1284


how to print electricity bill according to following charges first 100 units -1rs per unit for next 200 units-1.50 rs per unit without using conditions

3150


What does d mean?

1038


What is malloc calloc and realloc in c?

1250


What is an lvalue?

1031


Why array is used in c?

985


What is meant by recursion?

1020