Count Set Bits in An Integer
Count Set Bits in An Integer
Count Set Bits in An Integer
2.6
Write an efficient program to count number of 1s in binary representation of an integer.
Examples
Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits
Input : n = 13
Output : 3
Binary representation of 11 is 1101 and has 3 set bits
1 Initialize count: = 0
2 If integer n is not zero
(a) Do bitwise & with (n-1) and assign the value back to n
n: = n&(n-1)
(b) Increment count by 1
(c) go to step 2
3 Else return count
Since n = 0, return
count which is 2 now.
Time
Complexity: O(logn)
3. Using Lookup
table: We can count bits in
O(1) time using lookup
table. Please
seehttp://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable for details.
We can find one use of counting set bits at http://www.geeksforgeeks.org/?p=1465
Note: In GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate
function for counting set bits.
// C++ program to demonstrate __builtin_popcount()
#include <iostream>
using namespace std;
int main()
{
cout << __builtin_popcount (4) << endl;
cout << __builtin_popcount (15);
return 0;
}
Run on IDE
Output :
1
4
Check if a given array can represent Preorder Traversal of Binary Search Tree
3.9
Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search
Tree, else return false. Expected time complexity is O(n).
Examples:
Input: pre[] = {2, 4, 3}
Output: true
Given array can represent preorder traversal
of below tree
2
4
/
3
35 100
// Driver program
int main()
{
int pre1[] = {40, 30, 35, 80, 100};
int n = sizeof(pre1)/sizeof(pre1[0]);
canRepresentBST(pre1, n)? cout << "truen":
cout << "falsen";
return 0;
}
Run on IDE
Java
// Java program for an efficient solution to check if
// a given array can represent Preorder traversal of
// a Binary Search Tree
import java.util.Stack;
class BinarySearchTree {
Python
# Python program for an efficient solution to check if
# a given array can represent Preorder traversal of
# a Binary Search Tree
INT_MIN = -2**32
def canRepresentBST(pre):
return True
# Driver Program
pre1 = [40 , 30 , 35 , 80 , 100]
print "true" if canRepresentBST(pre1) == True else "false"
pre2 = [40 , 30 , 35 , 20 , 80 , 100]
print "true" if canRepresentBST(pre2) == True else "false"
Output:
true
false
Input : 1010
Output : 10
Input: 100001
Output: 33
Recommended: Please solve it on “PRACTICE ” first, before moving on
to the solution.
The idea is to extract the digits of given binary number starting from right most digit and keep a variable
dec_value. At the time of extracting digits from the binary number, multiply the digit with the proper base
(Power of 2) and add it to the variable dec_value. At the end, the variable dec_value will store the
required decimal number.
For Example:
If the binary number is 111.
dec_value = 1*(2^2) + 1*(2^1) + 1*(2^0) = 7
Below diagram explains how to convert ( 1010 ) to equivalent decimal value:
base = base*2;
}
return dec_value;
}
cout<<binaryToDecimal(num)<<endl;
}
Run on IDE
Output:
169
Note: The program works only with binary numbers in the range of integers. In case you want to work
with long binary numbers like 20 bits or 30 bit, you can use string variable to store the binary numbers.
Below is a similar program which uses string variable instead of integers to store binary value:
// C++ program to convert binary to decimal
// when input is represented as binary string.
#include<iostream>
#include<string>
using namespace std;
return dec_value;
}
rev = 0;
cout << "Number " << (n == rev ? "IS" : "IS NOT") << " a palindrome" << endl;
| |
|_|
Output: 10
| |
| | |
|__|_|
Output: 6
| || |
_|_||_||||||
first 2 and 3 and "1 unit" between second last 1 and last 2
Source: http://qa.geeksforgeeks.org/1875/trapping-rain-water
We strongly recommend that you click here and practice it, before moving
on to the solution.
An element of array can store water if there are higher bars on left and right. We can find amount of water
to be stored in every element by finding the heights of bars on left and right sides. The idea is to compute
amount of water that can be stored in every element of array. For example, consider the array {3, 0, 0, 2,
0, 4}, we can store two units of water at indexes 1 and 2, and one unit of water at index 2.
A Simple Solution is to traverse every array element and find the highest bars on left and right sides.
Take the smaller of two heights. The difference between smaller height and height of current element is the
amount of water that can be stored in this array element. Time complexity of this solution is O(n 2).
An Efficient Solution is to prre-compute highest bar on left and right of every bar in O(n) time. Then
use these pre-computed values to find the amount of water in every array element. Below is C++
implementation of this solution.
▪ C++
▪ Java
// C++ program to find maximum amount of water that can
// be trapped within given set of bars.
#include<bits/stdc++.h>
{
// left[i] contains height of tallest bar to the
// left of i'th bar including itself
int left[n];
// Initialize result
int water = 0;
return water;
}
// Driver program
int main()
{
int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
return 0;
Run on IDE
Output:
▪ C++
▪ Java
// C++ program to find maximum amount of water that can
// be trapped within given set of bars.
// Space Complexity : O(1)
#include<iostream>
{
// initialize output
int result = 0;
int lo = 0, hi = n-1;
{
if(arr[lo] < arr[hi])
left_max = arr[lo];
else
}
else
{
else
result += right_max - arr[hi];
hi--;
}
}
return result;
}
int main()
{
int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Maximum water that can be accumulated is "
Run on IDE
Output: