Count number of 1's in Java

Go down

Count number of 1's in Java

Post  skyboard on 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

View user profile

Back to top Go down

Back to top

- Similar topics

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