Challenge 1: Count Set Bits Or Number of 1 bit's
This is a traditional problem counting the number of set bits or 1's present in a number. Let’s see how we can count the set bits using the AND operator.
Table of Contents
This is a traditional problem counting the number of set bits or 1's present in a number.
Introduction
Let’s see how we can count the set bits using the AND operator.
What are set bits?
1 = set-bit
0 = unset-bit
Example:
Input: 5
Output: 0101 (in binary)
There are two set bits are two in the above example, as we have two 1s in the binary representation.
Problem statement
Write a program to count set bits of an integer.
Input: 125
Output: 6
Explanation: Input has six 1’s or set-bits so the output will be 6.
Intuition
In this program, a while-loop is iterated until the expression number > 0
is evaluated to 0
(false).
Let’s see the iterations for number = 125
.
Iterations
- After the first iteration,
number(125)
will be divided by2
, its value will be62
, and the count incremented to1
. - After the second iteration, the value of
number(62)
will be31
and the count incremented to2
. - After the third iteration, the value of
number(31)
will be15
, and the count incremented to3
. - And so on.
Then the expression is evaluated as false since the number
is 0
, and the loop terminates.
Iteration table
number | number = (number/2) | set/unset (1/0) | setbit count |
---|---|---|---|
125 | 62 | 1 | 1 |
62 | 31 | 0 | 1 |
31 | 15 | 1 | 2 |
15 | 7 | 1 | 3 |
7 | 3 | 1 | 4 |
3 | 1 | 1 | 5 |
1 | 0 | 1 | 6 |
Solutions
You will see the Java solution, which is then refactored for better readability.
Java
class CountSetBit {
private static int helper(int n) {
int ans = 0;
while (n > 0) {
if (n % 2 != 0) {
ans++;
}
n /= 2;
}
return ans;
}
public static void main(String[] args) {
int number = 125;
System.out.println("SetBit Count is : " + helper(number));
}
}
We can further rewrite this code using the &
operator as seen below.
public class CountSetBit {
private static int helper(int n) {
int count = 0;
while (n > 0) {
if ((n & 1) == 1) {
count++;
}
n >>= 1;
}
return count;
}
public static void main(String[] args) {
int number = 125;
System.out.println("SetBit Count is : " + helper(number));
}
}
This can be further simplified as shown below:
public class CountSetBit {
private static int helper(int n) {
int count = 0;
while (n > 0) {
count += (n & 1);
n >>= 1;
}
return count;
}
public static void main(String[] args) {
int number = 125;
System.out.println("SetBit Count is : " + helper(number));
}
}
Python
You will see the Python solution, which is then refactored for better readability.
def helper(n):
ans = 0
while n > 0:
if n % 2 != 0:
ans += 1
n //= 2
return ans
number = 125
print("SetBit Count is : ", helper(number))
We can further rewrite this code using the &
operator as seen below.
def helper(n):
count=0
while n > 0:
if ((n & 1) == 1):
count+=1
n >>= 1
return count
number=125
print("SetBit Count is : ",helper(number))
This can be further simplified as shown below:
def helper(n):
count=0
while n > 0:
count+=(n & 1)
n >>= 1
return count
number=125
print("SetBit Count is : ",helper(number))
JavaScript
You will see the JavaScript solution, which is then refactored for better readability.
const CountSetBits = (n) => {
let count = 0;
while (n > 0) {
if(n % 2 !== 0) {
count++;
}
n >>= 1;
}
return count;
}
console.log ('SetBit Count is', CountSetBits (125));
We can further rewrite this code using the &
operator as seen below.
const CountSetBits = (n) => {
let count = 0;
while (n > 0) {
if ((n & 1) === 1) {
count++;
}
n >>= 1
}
return count;
}
console.log ('SetBit Count is', CountSetBits (125));
This can be further simplified as shown below:
const CountSetBits = (n) => {
let count = 0;
while (n > 0) {
count += (n & 1);
n >>= 1;
}
return count;
}
console.log ('SetBit Count is', CountSetBits (125));
C++
You will see the C++ solution, which is then refactored for better readability.
#include <iostream>
using namespace std;
int helper(int n){
int count = 0;
while (n > 0){
if (n % 2 != 0){
count++;
}
n /= 2;
}
return count;
}
int main() {
int number = 125;
cout << "SetBit count is : " << helper(number);
return 0;
}
We can further rewrite this code using the &
operator as seen below.
#include <iostream>
using namespace std;
int helper(int n) {
int count = 0;
while (n > 0) {
if ((n & 1) == 1) {
count++;
}
n >>= 1;
}
return count;
}
int main() {
int number = 125;
cout << "SetBit count is : " << helper(number);
}
This can be further simplified as shown below:
#include <iostream>
using namespace std;
int helper(int n) {
int count = 0;
while (n > 0) {
count += (n & 1);
n >>= 1;
}
return count;
}
int main() {
int number = 125;
cout << "SetBit count is : " << helper(number);
return 0;
}
TypeScript
You will see the TypeScript solution, which is then refactored for better readability.
export const CountSetBits = (n: number): number => {
let count: number = 0;
while (n > 0) {
if (n % 2 !== 0) {
count++;
}
n >>= 1;
}
return count;
}
console.log('SetBit Count is', CountSetBits(125));
We can further rewrite this code using the &
operator as seen below.
export const CountSetBits = (n: number): number => {
let count: number = 0;
while (n > 0) {
if ((n & 1) === 1) {
count++;
}
n >>= 1
}
return count;
}
console.log('SetBit Count is', CountSetBits(125));
This can be further simplified as shown below:
export const CountSetBits = (n: number): number => {
let count: number = 0;
while (n > 0) {
count += (n & 1);
n >>= 1;
}
return count;
}
console.log('SetBit Count is', CountSetBits(125));
Time and space complexities
Time complexity: O(Total bits in n) / O(1) in simple terms
The time taken is proportional to the total bits in binary representation, which means
int
takes32
bits =>O(32 bits)
time.
long
takes64
bits =>O(64 bits)
time.
So, the time taken is O(Total bits in n
, which can be an int or long, etc.).
The run time depends on the number of bits in n. In the worst case, all bits in n are 1-bits. In the case of a 32-bit integer, the run time is O(32)
or O(1)
.
Space complexity: O(1) extra space
The space complexity is O(1)
. No extra space is allocated.
Coding exercise
Now, try to optimize the above snippets. There is a better way to solve this problem.
This problem is designed for your practice, so try to solve it yourself first. If you get stuck, you can always refer to the solution in the next lesson. Good luck!
Hint: Learn about "Brian Kernighan’s algorithm", because in next solution review, we are about to solve this with his approach.
// java
// TODO: finish the challenge or check next lesson for solution
class Solution{
public static int countSetBits(int n){
// Write - Your - Code- Here
return -1; // change this and return the correct setbit count
}
}
# python
# TODO: finish the challenge or check next lesson for solution
def Solution(n):
# Write - Your - Code- Here
return -1 # change this and return the correct setbit count
// javascript
// TODO: finish the challenge or check next lesson for solution
const CountSetBits = (number) => {
// Write - Your - Code- Here
return -1; // change this and return the correct setbit count
}
// c++
// TODO: finish the challenge or check next lesson for solution
#include <iostream>
using namespace std;
int countSetBits(int n) {
// Write - Your - Code- Here
return -1; // change this and return the correct setbit count
}
// typescript
// TODO: finish the challenge or check next lesson for solution
export const CountSetBits = (n: number): number => {
// Write - Your - Code- Here
return -1; // change this and return the correct setbit count
}
The solution will be explained in the next lesson.
Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.