Bits manipulation (Important tactics)
Last Updated :
07 May, 2024
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
// Direct XOR of all numbers from 1 to n
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;
}
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__
Python
# Direct XOR of all numbers from 1 to n
def 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 n
function 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 condition
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)
{
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
int 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 bits
import 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.
Python
# 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
def 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 code
n = 15
print(countValues(n))
# This code is contributed by akashish__
C#
// C# code to implement the approach
using 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 condition
function 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));
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
/*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__
Python
# 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__
Python
# 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);
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__
Python
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__
OutputBefore 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__
Python
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__
Python
# 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
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem