Code For NonGeek
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Count number of 1's in Java

Go down

Count number of 1's in Java Empty Count number of 1's in Java

Post  skyboard Sat Oct 01, 2011 7:12 pm

Best Way: O(m): m is number of 1

int numOnesInBinary(int number){
int numOnes=0;
while(number!=0){
number=number&(number-1);
numOnes++;
}
return numOnes;
}


Normal ways:

int numOnesInBinary(int number){
int numOnes=0;
while(number!=0){
if((number&1)==1)
numOnes++;
number=number>>>1;
}
return numOnes;
}

skyboard

Posts : 31
Join date : 2011-09-03

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum