Prerequisites: Bitwise operators in C, Bitwise Hacks for Competitive Programming, Bit Tricks for Competitive Programming
Table of Contents
- Compute XOR from 1 to n (direct method)
- Count of numbers (x) smaller than or equal to n such that n+x = n^x
- How to know if a number is a power of 2?
- Find XOR of all subsets of a set
- Find the number of leading, trailing zeroes and number of 1’s
- Convert binary code directly into an integer in C++
- The Quickest way to swap two numbers
- Simple approach to flip the bits of a number
- Finding the most significant set bit (MSB)
- Check if a number has bits in an alternate pattern
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
// Direct XOR of all numbers from 1 to nint 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;} |
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
# Direct XOR of all numbers from 1 to ndef computeXOR(n):    if (n % 4 is 0):        return n    if (n % 4 is 1):        return 1    if (n % 4 is 2):        return n + 1    else:        return 0Â
       # This code is contributed by akashish__ |
C#
using System;public 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(){}Â
Â
}Â
// This code is contributed by akashish__ |
Javascript
<script>Â
// Direct XOR of all numbers from 1 to nfunction computeXOR(n){    if (n % 4 == 0)        return n;    if (n % 4 == 1)        return 1;    if (n % 4 == 2)        return n + 1;    else        return 0;}Â
// This code is contributed by Shubham SinghÂ
</script> |
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++
// Count of numbers (x) smaller than or equal to n such that n+x = n^x:// here unset bits means zero bits#include <bits/stdc++.h>using namespace std;Â
// function to count number of values less than// equal to n that satisfy the given conditionint countValues(int n){    // unset_bits keeps track of count of un-set    // bits in binary representation of n    int unset_bits=0;    while (n)    {        if ((n & 1) == 0)            unset_bits++;        n=n>>1;    }Â
    // Return 2 ^ unset_bits i.e. pow(2,count of zero bits)    return 1 << unset_bits;}Â
// Driver codeint main(){Â Â Â Â int n = 15;Â Â Â Â cout << countValues(n);Â Â Â Â return 0;}Â
// contributed by akashish__ |
Java
// Count of numbers (x) smaller than or equal to n such that n+x = n^x:// here unset bits means zero bitsimport java.io.*;class GFG{Â
  // function to count number of values less than  // equal to n that satisfy the given condition  public static int countValues(int n)  {    // unset_bits keeps track of count of un-set    // bits in binary representation of n    int unset_bits = 0;    while (n > 0)    {      if ((n & 1) == 0)        unset_bits++;      n = n>>1;    }Â
    // Return 2 ^ unset_bits i.e. pow(2,count of zero bits)    return 1 << unset_bits;  }Â
  // Driver code  public static void main (String[] args) {    int n = 15;    System.out.print(countValues(n));  }}Â
// This code is contributed by poojaagrawal2. |
Python3
# Count of numbers (x) smaller than or equal to n such that n+x = n^x:# here unset bits means zero bitsÂ
# function to count number of values less than# equal to n that satisfy the given conditiondef countValues(n):       # unset_bits keeps track of count of un-set    # bits in binary representation of n    unset_bits=0    while (n):        if ((n & 1) == 0):            unset_bits+=1        n=n>>1Â
    # Return 2 ^ unset_bits i.e. pow(2,count of zero bits)    return 1 << unset_bitsÂ
# Driver coden = 15print(countValues(n))Â
# This code is contributed by akashish__ |
C#
// C# code to implement the approachusing System;using System.Collections.Generic;Â
class GFG {Â
  // Count of numbers (x) smaller than or equal to n such that n+x = n^x:  // here unset bits means zero bitsÂ
  // function to count number of values less than  // equal to n that satisfy the given condition  static int countValues(int n)  {Â
    // unset_bits keeps track of count of un-set    // bits in binary representation of n    int unset_bits = 0;    while (n > 0)    {      if ((n & 1) == 0)        unset_bits++;      n = n>>1;    }Â
    // Return 2 ^ unset_bits i.e. pow(2,count of zero bits)    return 1 << unset_bits;  }Â
  // Driver code  public static void Main()  {    int n = 15;    Console.Write(countValues(n));  }}Â
// This code is contributed by agrawalpoojaa976. |
Javascript
// Count of numbers (x) smaller than or equal to n such that n+x = n^x:// here unset bits means zero bitsÂ
// function to count number of values less than// equal to n that satisfy the given conditionfunction countValues(n){    // unset_bits keeps track of count of un-set    // bits in binary representation of n    let unset_bits=0;    while (n)    {        if ((n & 1) == 0)            unset_bits++;        n=n>>1;    }Â
    // Return 2 ^ unset_bits i.e. pow(2,count of zero bits)    return 1 << unset_bits;}Â
// Driver code    let n = 15;    document.write(countValues(n)); |
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 2bool isPowerOfTwo(int x){     // First x in the below expression is     // for the case when x is 0      return x && (!(x & (x - 1)));} |
Java
/*package whatever //do not write package name here */import java.io.*;Â
class GFG {Â
  // Function to check if x is power of 2  static public boolean isPowerOfTwo(int x)  {Â
    // First x in the below expression is    // for the case when x is 0     return (x != 0) && ((x & (x - 1)) == 0);  }Â
  public static void main (String[] args) {Â
Â
  }}// contributed by akashish__ |
Python3
# Function to check if x is power of 2def 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 2static 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 2function 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 codeimport 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 Codenumber = 0b011print(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); |
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 = 5b = 7print("Before Swapping, a = ",a," ","b = ",b)a ^= bb ^= aa ^= bprint("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__ |
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 patternbool 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 patterndef 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 patternfunction 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
This article is contributed by Sanchit Garg 1. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

[…] Bit Manipulation is a technique used in a variety of problems to get the solution in an optimized way. This technique is very effective from a Competitive Programming point of view. It is all about Bitwise Operators which directly works upon binary numbers or bits of numbers that help the implementation fast. Below are the Bitwise Operators that are used: […]