Count he number of 1s in bits of given number.
Example:
Input: 3
Output : 2 (because the binary representation of 3 is 0011, so the number of 1s are 2)
Input : 15
Output : 4 (because the binary representation of 15 is 1111, so the number of 1s are 4)
Implementation
Method 1:
int setBits(int n){
int count = 0;
while(n > 0){
if( (n&1) == 1)
count++;
n = n >> 1;
}
return count;
}
Time Complexity : Theta of logN
Method 2:
int setBits2(int n){
int count = 0;
while( n > 0){
count++;
n = n&(n-1);
}
return count;
}
Time Complexity : O(logN)
This algorithm goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop. In the worst case, it will pass once per bit. An integer
Example:
Input: 3
Output : 2 (because the binary representation of 3 is 0011, so the number of 1s are 2)
Input : 15
Output : 4 (because the binary representation of 15 is 1111, so the number of 1s are 4)
Implementation
Method 1:
int setBits(int n){
int count = 0;
while(n > 0){
if( (n&1) == 1)
count++;
n = n >> 1;
}
return count;
}
Time Complexity : Theta of logN
Method 2:
int setBits2(int n){
int count = 0;
while( n > 0){
count++;
n = n&(n-1);
}
return count;
}
Time Complexity : O(logN)
This algorithm goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop. In the worst case, it will pass once per bit. An integer
n
has log(n)
bits, hence the worst case is O(log(n)).
No comments:
Post a Comment