Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Last Updated :
28 Jan, 2022
Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can.
Boolean arrays have been used as a container to solve different problems. This article focuses on discussing the alternatives to boolean arrays.
Integer Variable as a container
In general, the Integer variable has 4 bytes (C++ taken into consideration) resulting in having 32 boolean bits to represent a number. For example, to represent 10, the boolean bits can be written as:
int a = 10
In Memory-
00000000000000000000000000001010 (Binary of 10 in 32-bit integer)
This means one can use these bits as a boolean value inside a boolean array of size 32. A 64-bit integer can be used to increase the size if needed.
How to use Integer variable as a container?
Let’s discuss in detail how to use the Integer variable as a container.
The first step is to initialize the integer variable as 0, to get the boolean container of size 32 with all bits initially false.
Set a bit to true:
Set any bit to true for any desired location by using bitwise operators such as AND, NOT, OR, and SHIFT operators. For, example, to set a bit to true at position 7-
Use shift and bitwise OR operator to make the ith bit to 1 (true)
int a = 0;
a |= (1 << 7);
Here a will become : 00000000000000000000000010000000
↑
0th bit
Step 1: First move 1 which is (..0001) in binary to 7 steps left to make it as (..10000000).
Step 2: Next, do bitwise or with the number.
Step 3: As 1 OR 0 = 1 and 1 OR 1 = 1, this will set the 7th bit to one without affecting other bits.
Set a bit to false:
For example, to reset a bit to false at position 7
Use shift and bitwise NOT and AND operator to make the ith bit to 0(false).
int a = 0;
a |= (1 << 7); // To set 7th bit
a &= ~(1 << 7); // To reset 7th bit
Step 1: First move our 1 which is (..0001) in binary to 7 steps left to make it as (..10000000).
Step 2: Invert the bits to look like (…1101111111).
Step 3: Perform AND operation with the number.
Step 4: As 1 AND 0 = 0, 0 AND 0 = 0, 1 AND 1 = 1, this will set the 7th bit to one without affecting other bits.
Get the value of ith bit:
For example, to get the value of the 7th bit-
Use AND operator to print.
int a = 0;
a |= (1<<7); // To set 7th bit
Print((a>>7)&1); // this will print 1(True)
a &= ~(1<<7); // To reset 7th bit
Print((a>>7)&1); // this will print 0(false)
Below is the implementation of the above approach:
C++
#include<iostream>
using namespace std;
int main()
{
int myBoolContainer = 0;
int workingBit = 7;
cout << "Setting " <<
workingBit << "th bit to 1\n" ;
myBoolContainer |= (1 << workingBit);
cout << "Value at " << workingBit <<
"th bit = " <<
((myBoolContainer >> workingBit) & 1) <<
"\n\n" ;
cout << "Resetting " << workingBit <<
"th bit to 0\n" ;
myBoolContainer &= ~(1 << 7);
cout << "Value at " << workingBit <<
"th bit = " <<
((myBoolContainer >> workingBit) & 1);
}
|
Java
import java.io.*;
class GFG
{
public static void main (String[] args)
{
int myBoolContainer = 0 ;
int workingBit = 7 ;
System.out.println(
"Setting " + workingBit +
"th bit to 1" );
myBoolContainer |= ( 1 << workingBit);
System.out.println(
"Value at " + workingBit+ "th bit = " +
((myBoolContainer >> workingBit) & 1 ) +
"\n" );
System.out.println(
"Resetting " + workingBit +
"th bit to 0" );
myBoolContainer &= ~( 1 << 7 );
System.out.println(
"Value at " + workingBit +
"th bit = " +
((myBoolContainer >>workingBit) & 1 ));
}
}
|
Python
myBoolContainer = 0 ;
workingBit = 7 ;
print ( "Setting " + str (workingBit) +
"th bit to 1" );
myBoolContainer | = ( 1 << workingBit);
print ( "Value at " + str (workingBit) +
"th bit = " + str ((myBoolContainer >>
workingBit) & 1 ) + "\n" );
print ( "Resetting " + str (workingBit) +
"th bit to 0" );
myBoolContainer & = ~( 1 << 7 );
print ( "Value at " + str (workingBit) +
"th bit = " + str ((myBoolContainer >>
workingBit) & 1 ))
|
C#
using System;
public class GFG {
static public void Main()
{
int myBoolContainer = 0;
int workingBit = 7;
Console.WriteLine( "Setting " + workingBit
+ "th bit to 1" );
myBoolContainer |= (1 << workingBit);
Console.WriteLine(
"Value at " + workingBit + "th bit = "
+ ((myBoolContainer >> workingBit) & 1) + "\n" );
Console.WriteLine( "Resetting " + workingBit
+ "th bit to 0" );
myBoolContainer &= ~(1 << 7);
Console.WriteLine(
"Value at " + workingBit + "th bit = "
+ ((myBoolContainer >> workingBit) & 1));
}
}
|
Javascript
var myBoolContainer = 0;
var workingBit = 7;
console.log( "Setting " + workingBit +
"th bit to 1\n" );
myBoolContainer |= (1 << workingBit);
console.log( "Value at " + workingBit +
"th bit = " + ((myBoolContainer >>
workingBit) & 1) + "\n\n" );
console.log( "Resetting " + workingBit +
"th bit to 0\n" );
myBoolContainer &= ~(1 << 7);
console.log( "Value at " + workingBit +
"th bit = " + ((myBoolContainer >>
workingBit) & 1));
|
Output
Setting 7th bit to 1
Value at 7th bit = 1
Resetting 7th bit to 0
Value at 7th bit = 0
Solve Pangram Strings:
Let’s solve the problem of pangram strings using the above approach.
Approach:
It is known that English alphabets of lower case range from (a-z) are having a count of no more than 26. So, in this approach, a bool array of constant size can be used. This will optimize the space complexity of the code.
Below is the implementation of the pangram strings using a boolean array:
C++
#include <iostream>
using namespace std;
bool checkIsPanagram(string sentence)
{
int n = 0;
for ( char &x:sentence)
{
if ( isalpha (x))
n |= (1 << ( tolower (x) - 'a' ));
}
return n == 67108863;
}
int main()
{
string s =
"Pack mY box witH fIve dozen liquor jugs" ;
cout << checkIsPanagram(s);
}
|
Java
import java.io.*;
class Panagram
{
public boolean checkIsPanagram(
String sentence)
{
int n = 0 ;
int size = sentence.length();
for ( int i = 0 ; i < size; i++)
{
char x = sentence.charAt(i);
if (Character.isAlphabetic(x))
{
n |= ( 1 << (Character.toLowerCase(x) - 'a' ));
}
}
return (n == 67108863 );
}
};
class GFG
{
public static void main (String[] args)
{
String s =
"Pack mY box witH fIve dozen liquor jugs" ;
Panagram panagram = new Panagram();
System.out.println(
panagram.checkIsPanagram(s));
}
}
|
Python
def isPanagram(sentence):
n = 0
for char in sentence:
if char.isalpha():
n | = ( 1 << ( ord (char.lower()) -
ord ( 'a' )))
return n = = 67108863
sentence =
"Pack mY box witH fIve dozen liquor jugs"
print (isPanagram(sentence))
|
C#
using System;
class Panagram
{
public bool checkIsPanagram(
String sentence)
{
int n = 0;
int size = sentence.Length;
for ( int i = 0; i < size; i++)
{
char x = sentence[i];
if ( char .IsLetter(x))
{
n |= (1 << ( char .ToLower(x) - 'a' ));
}
}
return (n == 67108863);
}
};
public class GFG
{
public static void Main(String[] args)
{
String s =
"Pack mY box witH fIve dozen liquor jugs" ;
Panagram panagram = new Panagram();
Console.WriteLine(
panagram.checkIsPanagram(s));
}
}
|
Javascript
<script>
function checkIsPanagram(sentence)
{
var n = 0;
var size = sentence.length;
for ( var i = 0; i < size; i++)
{
var x = sentence[i];
if (isAlphabetic(x))
{
n = n | (1 << (x.charCodeAt(0)- 'a' .charCodeAt(0)));
}
}
return (n == 67108863);
}
function isAlphabetic(str)
{
return /^[a-zA-Z()]+$/.test(str);
}
var s =
"Pack mY box witH fIve dozen liquor jugs" ;
document.write(checkIsPanagram(s));
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...