Open In App

Bitwise Hacks for Competitive Programming

Prerequisite: It is recommended to refer Interesting facts about Bitwise Operators 

How to set a bit in the number ‘num’:

If we want to set a bit at nth position in the number ‘num’, it can be done using the ‘OR’ operator( | ).  

Note: If the bit would be already set then it would remain unchanged.






#include<iostream>
using namespace std;
// num is the number and pos is the position
// at which we want to set the bit.
void set(int & num,int pos)
{
     // First step is shift '1', second
     // step is bitwise OR
     num |= (1 << pos);
}
int main()
{
     int num = 4, pos = 1;
     set(num, pos);
     cout << (int)(num) << endl;
     return 0;
}




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
        int num = 4, pos =1;
          num = set(num, pos);
          System.out.println(num);
    }
      public static int set(int num, int pos){
          // First step is shift '1', second
         // step is bitwise OR
          num |= (1 << pos);
          return num;
    }
}
 
// This code is contributed by geeky01adash.




# num = number, pos = position at which we want to set the bit
def set (num, pos):
  # First step = Shift '1'
  # Second step = Bitwise OR
  num |= (1 << pos)
  print(num)
   
num, pos = 4, 1
 
set(num, pos)
 
# This code is contributed by sarajadhav12052009




using System;
 
public class GFG{
 
    static public void Main ()
    {
      int num = 4, pos = 1;
      set(num, pos);
    }
   
    // num = number, pos = position at which we want to set the bit
    static public void set(int num, int pos)
    {
      // First Step: Shift '1'
      // Second Step: Bitwise OR
      num |= (1 << pos);
      Console.WriteLine(num);
    }
}
 
// This code is contributed by sarajadhav12052009




<script>
// num is the number and pos is the position
// at which we want to set the bit.
function set(num,pos)
{
     // First step is shift '1', second
     // step is bitwise OR
     num |= (1 << pos);
     console.log(parseInt(num));
}
 
let num = 4;
let pos = 1;
set(num, pos);
 
// This code is contributed by akashish__
 
</script>

Output
6

Time Complexity: O(1)
Auxiliary Space: O(1)



We have passed the parameter by ‘call by reference’ to make permanent changes in the number.

2. How to unset/clear a bit at n’th position in the number ‘num’ : 

Suppose we want to unset a bit at nth position in number ‘num’ then we have to do this with the help of ‘AND’ (&) operator.




#include <iostream>
using namespace std;
// First step is to get a number that  has all 1's except the given position.
void unset(int &num,int pos)
{
    //Second step is to bitwise and this  number with given number
    num &= (~(1 << pos));
}
int main()
{
    int num = 7;
    int  pos = 1;
    unset(num, pos);
    cout << num << endl;
    return 0;
}




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int num = 7, pos = 1;
        num = unset(num, pos);
        System.out.println(num);
    }
    public static int unset(int num, int pos)
    {
        // Second step is to bitwise and this  number with
        // given number
        num = num & (~(1 << pos));
        return num;
    }
}




# First Step: Getting which have all '1's except the
# given position
 
 
def unset(num, pos):
    # Second Step: Bitwise AND this number with the given number
    num &= (~(1 << pos))
    print(num)
 
 
num, pos = 7, 1
 
unset(num, pos)




using System;
 
public class GFG {
 
    static public void Main()
    {
        // First Step: Getting a number which have all '1's
        // except the given position
        int num = 7, pos = 1;
        unset(num, pos);
    }
    static public void unset(int num, int pos)
    {
        // Second Step: Bitwise AND this number with the
        // given number
        num &= (~(1 << pos));
        Console.WriteLine(num);
    }
}




// First step is to get a number that  has all 1's except the given position.
function unset(num,pos)
{
    //Second step is to bitwise and this  number with given number
    num &= ( ~ (1 << pos));
    return num;
}
let num = 7;
let  pos = 1;
console.log(unset(num, pos));
 
// This code is contributed by akashish__

Output
5

Time Complexity: O(1)
Auxiliary Space: O(1)

3.  Toggling a bit at nth position :

Toggling means to turn bit ‘on'(1) if it was ‘off'(0) and to turn ‘off'(0) if it was ‘on'(1) previously. We will be using the ‘XOR’ operator here which is this ‘^’. The reason behind the ‘XOR’ operator is because of its properties. 




#include <iostream>
using namespace std;
// First step is to shift 1,Second step is to XOR with given
// number
void toggle(int& num, int pos) { num ^= (1 << pos); }
int main()
{
    int num = 4;
    int pos = 1;
    toggle(num, pos);
    cout << num << endl;
    return 0;
}




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
        int num = 4, pos =1;
          num = toggle(num, pos);
          System.out.println(num);
    }
      public static int toggle(int num, int pos){
          // First step is to shift 1,Second step is to XOR with given number
        num ^= (1 << pos);
          return num;
    }
}
 
// This code is contributed by geeky01adash.




def toggle(num, pos):
  # First Step: Shifts '1'
  # Second Step: XOR num
  num ^= (1 << pos)
  print(num)
   
   
num, pos = 4, 1
 
toggle(num, pos)
 
# This code is contributed by sarajadhav12052009




using System;
 
public class GFG{
 
    static public void Main ()
    {
      int num = 4, pos = 1;
      toggle(num, pos);
    }
    static public void toggle(int num, int pos)
    {
      // First Step: Shift '1'
      // Second Step: XOR num
      num ^= (1 << pos);
      Console.WriteLine(num);
    }
}
 
// This code is contributed by sarajadhav12052009




function toggle(num, pos) {
 
    // First step is to shift 1,Second step is to XOR with given number
    num ^= (1 << pos);
    return num;
}
 
let num = 4,
    pos = 1;
num = toggle(num, pos);
console.log(num);
 
// This code is contributed by Prajwal Kandekar

Output
6

Time Complexity: O(1)
Auxiliary Space: O(1)

4. Checking if bit at nth position is set or unset: 

It is quite easily doable using the ‘AND’ operator.




#include <iostream>
using namespace std;
 
bool at_position(int num, int pos)
{
    bool bit = num & (1 << pos);
    return bit;
}
 
int main()
{
    int num = 5;
    int pos = 0;
    bool bit = at_position(num, pos);
    cout << bit << endl;
    return 0;
}




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int num = 5;
        int pos = 0;
        int bit = at_position(num, pos);
        System.out.println(bit);
    }
    public static int at_position(int num, int pos)
    {
        int bit = num & (1 << pos);
        return bit;
    }
}




# code
def at_position(num,pos):
    bit = num & (1<<pos)
    return bit
   
num = 5
pos = 0
bit = at_position(num, pos)
print(bit)




using System;
 
class GFG {
    static void Main(string[] args)
    {
        int num = 5;
        int pos = 0;
        int bit = at_position(num, pos);
        Console.WriteLine(bit);
    }
 
    static int at_position(int num, int pos)
    {
        int bit = num & (1 << pos);
        return bit;
    }
}




<script>
function at_position(num,pos)
{
 return num & (1<<pos);
}
let num = 5;
let pos = 0;
console.log(at_position(num, pos));
// contributed by akashish__
</script>

Output
1

Time Complexity: O(1)
Auxiliary Space: O(1)

Observe that we have first left shifted ‘1’ and then used ‘AND’ operator to get bit at that position. So if there is ‘1’ at position ‘pos’ in ‘num’, then after ‘AND’ our variable ‘bit’ will store ‘1’ else if there is ‘0’ at position ‘pos’ in the number ‘num’ than after ‘AND’ our variable bit will store ‘0’.

Some more quick hacks: 

This is also the ‘1s complement of number’.




#include <iostream>
using namespace std;
int main()
{
    int num = 4;
 
    // Inverting every bit of number num
    cout << (~num);
    return 0;
}




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
        int num = 4;
       
          // Inverting every bit of number num
          num = (~num);
          System.out.println(num);
    }
}




num = 4
 
# Inverting every bit of number num
print(~num)




using System;
 
public class GFG{
 
    static public void Main ()
    {
      int num = 4;
       
      // Inverting every bit of number num
      Console.WriteLine(~num);
    }
}




<script>
let num = 4;
 
    // Inverting every bit of number num
    console.log(~num);
     
    
</script>

Output
-5

Time Complexity: O(1)
Auxiliary Space: O(1)

So formally we can have 2’s complement by finding 1s complement and adding 1 to the result i.e (~num+1) or what else we can do is using ‘-‘ operator.




#include <iostream>
using namespace std;
int main()
{
    int num = 4;
    int twos_complement = -num;
    cout << "This is two's complement " << twos_complement << endl;
    cout << "This is also two's complement " << (~num+1) << endl;
    return 0;
}




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int num = 4;
        int twos_complement = -num;
        System.out.println("This is two's complement "
             + twos_complement);
        System.out.println("This is also two's complement "
             + (~num + 1));
    }
}
 
// This code is contributed by geeky01adash.




num = 4
twos_complement = -num
 
print(f"This is two's complement {twos_complement}")
print(f"This is also two's complement {~num + 1}")
 
# This code is contributed by sarajadhav12052009




using System;
 
public class GFG{
 
    static public void Main ()
    {
      int num = 4;
      int twos_complement = -num;
       
      Console.WriteLine("This is two's complement " + twos_complement);
      Console.WriteLine("This is also two's complement " + (~num+1));
    }
}
 
// This code is contributed by sarajadhav12052009




<script>
let num = 4;
let twos_complement = -num;
console.log("This is two's complement " + twos_complement);
console.log("This is also two's complement " + (~num+1));
 
// This code is contributed by akashish__
</script>

Output
This is two's complement -4
This is also two's complement -4

Time Complexity: O(1)
Auxiliary Space: O(1)

 Stripping off the lowest set bit :

In many situations we want to strip off the lowest set bit for example in Binary Indexed tree data structure, counting number of set bit in a number. We do something like this:  

X = X & (X-1)

But how does it even work? Let us see this by taking an example, let X = 1100.




#include <iostream>
using namespace std;
void strip_last_set_bit(int &num)
{
    num = num & (num-1);
}
int main()
{
    int num = 7;
    strip_last_set_bit(num);
    cout << num << endl;
    return 0;
}




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int num = 7;
        num = strip_last_set_bit(num);
        System.out.println(num);
    }
    public static int strip_last_set_bit(int num)
    {
        return num & (num - 1);
    }
}




def strip_last_set_bit(num):
    num &= (num - 1)
    print(num)
 
 
num = 7
 
strip_last_set_bit(num)




using System;
 
public class GFG{
 
    static public void Main ()
    {
      int num = 7;
      strip_last_set_bit(num);
    }
    static public void strip_last_set_bit(int num)
    {
      num &= (num - 1);
      Console.WriteLine(num);
    }
}




<script>
function strip_last_set_bit(num)
{
    return num & (num-1);
}
 
let num = 7;
 
console.log(strip_last_set_bit(num));
</script>

Output
6

Time Complexity: O(1)
Auxiliary Space: O(1)

Getting the lowest set bit of a number:

This is done by using the expression ‘X &(-X)’Let us see this by taking an example: Let X = 00101100. So ~X(1’s complement) will be ‘11010011’ and 2’s complement will be (~X+1 or -X) i.e.  ‘11010100’.So if we ‘AND’ original number ‘X’ with its two’s complement which is ‘-X’, we get the lowest set bit. 

  00101100
& 11010100
-----------
  00000100




#include <iostream>
using namespace std;
int lowest_set_bit(int num)
{
    int ret = num & (-num);
    return ret;
}
int main()
{
    int num = 10;
    int ans = lowest_set_bit(num);
    cout << ans << endl;
    return 0;
}




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int num = 10;
        int ans = lowest_set_bit(num);
        System.out.println(ans);
    }
    public static int lowest_set_bit(int num)
    {
        int ret = num & (-num);
        return ret;
    }
}




def lowest_set_bit(num):
    num &= (-num)
    print(num)
 
 
num = 10
 
lowest_set_bit(num)




// Function for lowest set bit
function lowest_set_bit(num)
{
    // Taking and of num and -ve of num
    let ret = num & (-num);
    return ret;
}
 
// Driver code
let num = 10
let ans = lowest_set_bit(num)
console.log(ans)




using System;
 
public class GFG {
 
    static public void Main()
    {
        int num = 10;
        lowest_set_bit(num);
    }
    static public void lowest_set_bit(int num)
    {
        num &= (~num + 1);
        Console.WriteLine(num);
    }
}

Output
2

Time Complexity: O(1)
Auxiliary Space: O(1)

Division by 2 and Multiplication by 2 are very frequently that too in loops in Competitive Programming so using Bitwise operators can help in speeding up the code.

Divide by 2 using the right shift operator:

00001100 >> 1 (00001100 is 12)
------------
00000110 (00000110 is 6)




#include <iostream>
using namespace std;
int main()
{
    int num = 12;
    int ans = num>>1;
    cout << ans << endl;
    return 0;
}




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int num = 12;
        int ans = num >> 1;
        System.out.println(ans);
    }
}




num = 12
print(num >> 1)




using System;
 
public class GFG{
 
    static public void Main ()
    {
      int num = 12;
      Console.WriteLine(num >> 1);
    }
}




<script>
var num = 12;
var ans = num>>1;
console.log(ans);
</script>

Output
6

Time Complexity: O(1)
Auxiliary Space: O(1)

Multiply by 2 using the left shift operator:

00001100 << 1 (00001100 is 12)
------------
00011000 (00000110 is 24)




#include <iostream>
using namespace std;
int main()
{
    int num = 12;
    int ans = num<<1;
    cout << ans << endl;
    return 0;
}




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
          int num = 12;
        int ans = num<<1;
        System.out.println(ans);
    }
}
 
// This code is contributed by geeky01adash.




using System;
 
public class GFG{
 
    static public void Main ()
    {
      int num = 12;
      Console.WriteLine(num << 1);
    }
}
 
// This code is contributed by sarajadhav12052009




# Python program for the above approach
 
num = 12
ans = num<<1
print(ans)
 
# This code is contributed by Shubham Singh




<script>
// Javascript program for the above approach
 
var num = 12;
var ans = num<<1;
document.write(ans);
 
//This code is contributed by Shubham Singh
</script>

Output
24

Time Complexity: O(1)
Auxiliary Space: O(1)

Bit Tricks for Competitive Programming
Refer BitWise Operators Articles for more articles on Bit Hacks.

 


Article Tags :