Open In App
Related Articles

Bits manipulation (Important tactics)

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Prerequisites: Bitwise operators in C, Bitwise Hacks for Competitive Programming, Bit Tricks for Competitive Programming

Table of Contents

1. Compute XOR from 1 to n (direct method):

The  problem can be solved based on the following observations:

Say x = n%4. The XOR value depends on the value if x. If

  • x = 0, then the answer is n.
  • x = 1, then answer is 1.
  • x = 2, then answer is n+1.
  • x = 3, then answer is 0.

Below is the implementation of the above approach.

CPP


                    

Java

/*package whatever //do not write package name here */
import java.io.*;
 
class GFG
{
   
  // Direct XOR of all numbers from 1 to n
  public static int computeXOR(int n)
  {
    if (n % 4 == 0)
      return n;
    if (n % 4 == 1)
      return 1;
    if (n % 4 == 2)
      return n + 1;
    else
      return 0;
  }
 
  public static void main (String[] args) {
 
  }
}
 
// This code is contributed by akashish__

                    

Python3

<div id="highlighter_808959" class="syntaxhighlighter nogutter  "><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="comments"># Direct XOR of all numbers from 1 to n</code></div><div class="line number2 index1 alt1"><code class="keyword">def</code> <code class="plain">computeXOR(n):</code></div><div class="line number3 index2 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(n </code><code class="keyword">%</code> <code class="value">4</code> <code class="keyword">is</code> <code class="value">0</code><code class="plain">):</code></div><div class="line number4 index3 alt1"><code class="undefined spaces">        </code><code class="keyword">return</code> <code class="plain">n</code></div><div class="line number5 index4 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(n </code><code class="keyword">%</code> <code class="value">4</code> <code class="keyword">is</code> <code class="value">1</code><code class="plain">):</code></div><div class="line number6 index5 alt1"><code class="undefined spaces">        </code><code class="keyword">return</code> <code class="value">1</code></div><div class="line number7 index6 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(n </code><code class="keyword">%</code> <code class="value">4</code> <code class="keyword">is</code> <code class="value">2</code><code class="plain">):</code></div><div class="line number8 index7 alt1"><code class="undefined spaces">        </code><code class="keyword">return</code> <code class="plain">n </code><code class="keyword">+</code> <code class="value">1</code></div><div class="line number9 index8 alt2"><code class="undefined spaces">    </code><code class="keyword">else</code><code class="plain">:</code></div><div class="line number10 index9 alt1"><code class="undefined spaces">        </code><code class="keyword">return</code> <code class="value">0</code></div><div class="line number11 index10 alt2"> </div><div class="line number12 index11 alt1"><code class="undefined spaces">      </code> </div><div class="line number13 index12 alt2"><code class="comments"># This code is contributed by akashish__</code></div></div></td></tr></tbody></table></div>

                    

C#

<div id="highlighter_429628" class="syntaxhighlighter nogutter  "><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="keyword">using</code> <code class="plain">System;</code></div><div class="line number2 index1 alt1"><code class="keyword">public</code> <code class="keyword">class</code> <code class="plain">GFG</code></div><div class="line number3 index2 alt2"><code class="plain">{</code></div><div class="line number4 index3 alt1"> </div><div class="line number5 index4 alt2"><code class="undefined spaces">  </code><code class="comments">// Direct XOR of all numbers from 1 to n</code></div><div class="line number6 index5 alt1"><code class="undefined spaces">  </code><code class="keyword">public</code> <code class="keyword">static</code> <code class="keyword">int</code> <code class="plain">computeXOR(</code><code class="keyword">int</code> <code class="plain">n)</code></div><div class="line number7 index6 alt2"><code class="undefined spaces">  </code><code class="plain">{</code></div><div class="line number8 index7 alt1"> </div><div class="line number9 index8 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(n % 4 == 0)</code></div><div class="line number10 index9 alt1"> </div><div class="line number11 index10 alt2"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="plain">n;</code></div><div class="line number12 index11 alt1"> </div><div class="line number13 index12 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(n % 4 == 1)</code></div><div class="line number14 index13 alt1"> </div><div class="line number15 index14 alt2"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="plain">1;</code></div><div class="line number16 index15 alt1"> </div><div class="line number17 index16 alt2"><code class="undefined spaces">    </code><code class="keyword">if</code> <code class="plain">(n % 4 == 2)</code></div><div class="line number18 index17 alt1"> </div><div class="line number19 index18 alt2"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="plain">n + 1;</code></div><div class="line number20 index19 alt1"> </div><div class="line number21 index20 alt2"><code class="undefined spaces">    </code><code class="keyword">else</code></div><div class="line number22 index21 alt1"> </div><div class="line number23 index22 alt2"><code class="undefined spaces">      </code><code class="keyword">return</code> <code class="plain">0;</code></div><div class="line number24 index23 alt1"> </div><div class="line number25 index24 alt2"><code class="undefined spaces">  </code><code class="plain">}</code></div><div class="line number26 index25 alt1"><code class="undefined spaces">  </code><code class="keyword">public</code> <code class="keyword">static</code> <code class="keyword">void</code> <code class="plain">Main(){}</code></div><div class="line number27 index26 alt2"> </div><div class="line number28 index27 alt1"> </div><div class="line number29 index28 alt2"><code class="plain">}</code></div><div class="line number30 index29 alt1"> </div><div class="line number31 index30 alt2"><code class="comments">// This code is contributed by akashish__</code></div></div></td></tr></tbody></table></div>

                    

Javascript


                    

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

Refer Compute XOR from 1 to n for details.

2. Count of numbers (x) smaller than or equal to n such that n+x = n^x:

The count of such numbers x can be counted using the following mathematical trick. 

The count = pow(2, count of zero bits).

C++


                    

Java


                    

Python3


                    

C#


                    

Javascript


                    

Output
1

Refer Equal Sum and XOR for details.

Time complexity: O(log n)

Auxiliary Space: O(1)

3. How to know if a number is a power of 2?

This can be solved based on the following fact:

If a number N is a power of 2, then the bitwise AND of N and N-1 will be 0. But this will not work if N is 0. So just check these two conditions, if any of these two conditions is true.

Refer check if a number is power of two for details.

Below is the implementation of the above approach.

CPP

//  Function to check if x is power of 2
bool isPowerOfTwo(int x)
{
     // First x in the below expression is
     // for  the case when x is 0
     return x && (!(x & (x - 1)));
}

                    

Java


                    

Python3

#  Function to check if x is power of 2
def isPowerOfTwo(x):
   
  # First x in the below expression is
  # for  the case when x is 0
  return x and (not(x & (x - 1)))
 
# This code is contributed by akashish__

                    

C#

using System;
 
public class GFG{
   
  //  Function to check if x is power of 2
static public bool isPowerOfTwo(int x)
{
     // First x in the below expression is
     // for  the case when x is 0
       return (x != 0) && ((x & (x - 1)) == 0);
}
 
    static public void Main (){
 
    }
}
 
// This code is contributed by akashish__

                    

Javascript

//  Function to check if x is power of 2
function isPowerOfTwo(x)
{
     // First x in the below expression is
     // for  the case when x is 0
     return x && (!(x & (x - 1)));
}
 
// This code is contributed by akashish__

                    

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

4. Find XOR of all subsets of a set

We can do it in O(1) time. The answer is always 0 if the given set has more than one element. For sets with a single element, the answer is the value of the single element. 

Refer XOR of the XOR’s of all subsets for details.

5. Find the number of leading, trailing zeroes and number of 1’s

We can quickly find the number of leading, trailing zeroes and number of 1’s in a binary code of an integer in C++ using GCC. 

It can be done by using inbuilt functions i.e.

Number of leading zeroes: __builtin_clz(x)
Number of trailing zeroes : __builtin_ctz(x)
Number of 1-bits: __builtin_popcount(x) 

Refer GCC inbuilt functions for details.

6. Convert binary code directly into an integer in C++

CPP

// Conversion into Binary code
 
#include <iostream>
using namespace std;
 
int main()
{
    auto number = 0b011;
    cout << number;
    return 0;
}

                    

Java

/*package whatever //do not write package name here */
// Conversion into Binary code
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        int number = 0b011;
        System.out.println(number);
    }
}
 
// This code is contributed by akashish__

                    

Python3

# Python Code
number = 0b011
print(number)
 
# This code is contributed by akashish__

                    

C#

// Conversion into Binary code
 
using System;
 
public class GFG {
 
    static public void Main()
    {
 
        // Code
        int number = 0b011;
        Console.WriteLine(number);
    }
}
 
// This code is contributed by karthik

                    

Javascript

// Conversion into Binary code
 
let number = 0b011;
console.log(number);

                    

Output
3

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

7. The Quickest way to swap two numbers:

Two numbers can be swapped easily using the following bitwise operations:

a ^= b;
b ^= a; 
a ^= b;

C++

#include <iostream>
using namespace std;
 
int main()
{
    int a = 5;
      int b = 7;
      cout<<"Before Swapping, a = "<<a<<" "<<"b = "<<b<<endl;
    a ^= b;
    b ^= a;
    a ^= b;
      cout<<"After Swapping, a = "<<a<<" "<<"b = "<<b<<endl;
    return 0;
}
 
// This code is contributed by akashish__

                    

Java

/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
 
class GFG {
  public static void main(String[] args)
  {
    int a = 5;
    int b = 7;
    System.out.print("Before Swapping, a = ");
    System.out.print(a);
    System.out.print(" ");
    System.out.print("b = ");
    System.out.print(b);
    System.out.println("");
    a ^= b;
    b ^= a;
    a ^= b;
    System.out.print("After Swapping, a = ");
    System.out.print(a);
    System.out.print(" ");
    System.out.print("b = ");
    System.out.print(b);
  }
}
 
// This code is contributed by akashish__

                    

Python3

a = 5
b = 7
print("Before Swapping, a = ",a," ","b = ",b)
a ^= b
b ^= a
a ^= b
print("After Swapping, a = ",a," ","b = ",b)
 
# This code is contributed by akashish__

                    

C#

using System;
 
public class GFG {
 
    static public void Main()
    {
 
        int a = 5;
        int b = 7;
        Console.WriteLine("Before Swapping, a = " + a + " "
                          + "b = " + b);
        a ^= b;
        b ^= a;
        a ^= b;
        Console.WriteLine("After Swapping, a = " + a + " "
                          + "b = " + b);
    }
}
// This code is contributed by akashish__

                    

Javascript

let a = 5;
let b = 7;
console.log("Before Swapping, a = " , a , " " , "b = " , b);
a ^= b;
b ^= a;
a ^= b;
console.log("After Swapping, a = " , a , " " , "b = " , b);
 
// This code is contributed by akashish__

                    

Output
Before Swapping, a = 5 b = 7
After Swapping, a = 7 b = 5

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

Refer swap two numbers for more details.  

8. Finding the most significant set bit (MSB):

We can find the most significant set bit in O(1) time for a fixed size integer. For example below code is for 32-bit integer.  

C++

int setBitNumber(int n)
{
    // Below steps set bits after
    // MSB (including MSB)
 
    // Suppose n is 273 (binary
    // is 100010001). It does following
    // 100010001 | 010001000 = 110011001
    n |= n >> 1;
 
    // This makes sure 4 bits
    // (From MSB and including MSB)
    // are set. It does following
    // 110011001 | 001100110 = 111111111
    n |= n >> 2;
 
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
 
    // Increment n by 1 so that
    // there is only one set bit
    // which is just before original
    // MSB. n now becomes 1000000000
    n = n + 1;
 
    // Return original MSB after shifting.
    // n now becomes 100000000
    return (n >> 1);
}

                    

Java

/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
 
  public static int setBitNumber(int n)
  {
    // Below steps set bits after
    // MSB (including MSB)
 
    // Suppose n is 273 (binary
    // is 100010001). It does following
    // 100010001 | 010001000 = 110011001
    n |= n >> 1;
 
    // This makes sure 4 bits
    // (From MSB and including MSB)
    // are set. It does following
    // 110011001 | 001100110 = 111111111
    n |= n >> 2;
 
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
 
    // Increment n by 1 so that
    // there is only one set bit
    // which is just before original
    // MSB. n now becomes 1000000000
    n = n + 1;
 
    // Return original MSB after shifting.
    // n now becomes 100000000
    return (n >> 1);
  }
 
 
  public static void main (String[] args) {
  }
}
 
// This code is contributed by akashish__

                    

Python3

def setBitNumber(n):
    # Below steps set bits after
    # MSB (including MSB)
 
    # Suppose n is 273 (binary
    # is 100010001). It does following
    # 100010001 | 010001000 = 110011001
    n |= n >> 1
 
    # This makes sure 4 bits
    # (From MSB and including MSB)
    # are set. It does following
    # 110011001 | 001100110 = 111111111
    n |= n >> 2
 
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
 
    # Increment n by 1 so that
    # there is only one set bit
    # which is just before original
    # MSB. n now becomes 1000000000
    n = n + 1
 
    # Return original MSB after shifting.
    # n now becomes 100000000
    return (n >> 1)
   
# This code is contributed by akashish__

                    

C#

using System;
 
public class GFG{
   
  public static int setBitNumber(int n)
{
    // Below steps set bits after
    // MSB (including MSB)
 
    // Suppose n is 273 (binary
    // is 100010001). It does following
    // 100010001 | 010001000 = 110011001
    n |= n >> 1;
 
    // This makes sure 4 bits
    // (From MSB and including MSB)
    // are set. It does following
    // 110011001 | 001100110 = 111111111
    n |= n >> 2;
 
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
 
    // Increment n by 1 so that
    // there is only one set bit
    // which is just before original
    // MSB. n now becomes 1000000000
    n = n + 1;
 
    // Return original MSB after shifting.
    // n now becomes 100000000
    return (n >> 1);
}
 
    static public void Main (){
 
        // Code
    }
}
 
// This code is contributed by akashish__

                    

Javascript

function setBitNumber(n)
{
    // Below steps set bits after
    // MSB (including MSB)
 
    // Suppose n is 273 (binary
    // is 100010001). It does following
    // 100010001 | 010001000 = 110011001
    n |= n >> 1;
 
    // This makes sure 4 bits
    // (From MSB and including MSB)
    // are set. It does following
    // 110011001 | 001100110 = 111111111
    n |= n >> 2;
 
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
 
    // Increment n by 1 so that
    // there is only one set bit
    // which is just before original
    // MSB. n now becomes 1000000000
    n = n + 1;
 
    // Return original MSB after shifting.
    // n now becomes 100000000
    return (n >> 1);
}
 
// This code is contributed by akashish__

                    

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

Refer Find most significant set bit of a number for details. 

9. Check if a number has bits in an alternate pattern

We can quickly check if bits in a number are in an alternate pattern (like 101010). 

Compute bitwise XOR (XOR denoted using ^) of n and (n >> 1). If n has an alternate pattern, then n ^ (n >> 1) operation will produce a number having all bits set.

Below is the implementation of the above approach.

C++

// function to check if all the bits
// are set or not in the binary
// representation of 'n'
static bool allBitsAreSet(int n)
{
    // if true, then all bits are set
    if (((n + 1) & n) == 0)
        return true;
 
    // else all bits are not set
    return false;
}
 
// Function to check if a number
// has bits in alternate pattern
bool bitsAreInAltOrder(unsigned int n)
{
    unsigned int num = n ^ (n >> 1);
 
    // To check if all bits are set in 'num'
    return allBitsAreSet(num);
}

                    

Java

/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
 
  // function to check if all the bits
  // are set or not in the binary
  // representation of 'n'
  public static boolean allBitsAreSet(long n)
  {
 
    // if true, then all bits are set
    if (((n + 1) & n) == 0)
      return true;
 
    // else all bits are not set
    return false;
  }
 
  // Function to check if a number
  // has bits in alternate pattern
  public static boolean bitsAreInAltOrder(long n)
  {
    long num = n ^ (n >> 1);
 
    // To check if all bits are set in 'num'
    return allBitsAreSet(num);
  }
  public static void main (String[] args) {
 
  }
}
 
// This code is contributed by akashish__

                    

Python3

# function to check if all the bits
# are set or not in the binary
# representation of 'n'
def allBitsAreSet(n):
  # if true, then all bits are set
  if (((n + 1) & n) == 0):
    return True
 
  # else all bits are not set
  return False
 
# Function to check if a number
# has bits in alternate pattern
def bitsAreInAltOrder(n):
  num = n ^ (n >> 1)
 
  # To check if all bits are set in 'num'
  return allBitsAreSet(num)
 
 
# This code is contributed by akashish__

                    

C#

using System;
public class GFG
{
 
    // function to check if all the bits
    // are set or not in the binary
    // representation of 'n'
    public static bool allBitsAreSet(uint n)
    {
       
        // if true, then all bits are set
        if (((n + 1) & n) == 0)
            return true;
 
        // else all bits are not set
        return false;
    }
 
    // Function to check if a number
    // has bits in alternate pattern
    public static bool bitsAreInAltOrder(uint n)
    {
        uint num = n ^ (n >> 1);
 
        // To check if all bits are set in 'num'
        return allBitsAreSet(num);
    }
 
    static public void Main() {}
}
 
// This code is contributed by akashish__

                    

Javascript

// function to check if all the bits
// are set or not in the binary
// representation of 'n'
function allBitsAreSet(n)
{
    // if true, then all bits are set
    if (((n + 1) & n) == 0)
        return true;
 
    // else all bits are not set
    return false;
}
 
// Function to check if a number
// has bits in alternate pattern
function bitsAreInAltOrder(n)
{
    let num = n ^ (n >> 1);
 
    // To check if all bits are set in 'num'
    return allBitsAreSet(num);
}
 
// This code is contributed by akashish__

                    

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

Refer check if a number has bits in alternate pattern for details.

DSA Self Paced Course

DSA Self Paced Course




Last Updated : 10 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads