Bit stands for binary digit. A bit is the basic unit of information and can only have one of two possible values that is 0 or 1. In our world, we usually with numbers using the decimal base. In other words. we use the digit 0 to 9 However, there are other number representations that can be quite useful such as the binary number systems.

Introduction to Bitwise Algorithms – Data Structures and Algorithms Tutorial
Unlike humans, computers have no concepts of words and numbers. They receive data encoded at the lowest level as a series of zeros and ones (0 and 1). These are called bits, and they are the basis for all the commands they receive. We’ll begin by learning about bits and then explore a few algorithms for manipulating bits. We’ll then explore a few algorithms for manipulating bits. The tutorial is meant to be an introduction to bit algorithms for programmers.
What is Bitwise Algorithms?
Bitwise algorithms refer to algorithms that perform operations on individual bits or bit patterns within computer data. These algorithms uses the binary representation of data and use the fundamental bitwise operations such as AND, OR, XOR, NOT, and bit shifting to manipulate and extract information from the data.
Bitwise algorithms are usually faster and use less memory than regular arithmetic operations because they work directly with the binary representation of data. This often leads to faster execution times and reduced memory usage.
Bitwise Operators / Basics of Bit manipulation
An algorithmic operation known as bit manipulation involves the manipulation of bits at the bit level (bitwise). Bit manipulation is all about these bitwise operations. They improve the efficiency of programs by being primitive, fast actions.
The computer uses this bit manipulation to perform operations like addition, subtraction, multiplication, and division are all done at the bit level. This operation is performed in the arithmetic logic unit (ALU) which is a part of a computer’s CPU. Inside the ALU, all such mathematical operations are performed.
There are different bitwise operations used in bit manipulation. These bit operations operate on the individual bits of the bit patterns. Bit operations are fast and can be used in optimizing time complexity.
The main bitwise operators are:
- AND (&)
- OR (|)
- XOR (^)
- NOT (~)
- Left Shift (<<)
- Right Shift (>>)

Bitwise Operator Truth Table
Bitwise AND Operator (&)
The bitwise AND operator is denoted using a single ampersand symbol, i.e. &. The & operator takes two equal-length bit patterns as parameters. The two-bit integers are compared. If the bits in the compared positions of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.

Truth table of AND operator
Example:
Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y

Bitwise ANDof (7 & 4)
Implementation of AND operator:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 7, b = 4;
int result = a & b;
cout << result << endl;
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main (String[] args) {
int a = 7, b = 4;
int result = a & b;
System.out.println(result);
}
}
// This code is contributed by lokeshmvs21.
Python
a = 7
b = 4
result = a & b
print(result)
# This code is contributed by akashish__
C#
using System;
public class GFG{
static public void Main (){
int a = 7, b = 4;
int result = a & b;
Console.WriteLine(result);
}
}
// This code is contributed by akashish__
JavaScript
let a = 7, b = 4;
let result = a & b;
console.log(result);
// This code is contributed by akashish__
Bitwise OR Operator (|)
The | Operator takes two equivalent length bit designs as boundaries; if the two bits in the looked-at position are 0, the next bit is zero. If not, it is 1.
.png)
Example:
Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise OR of both X, y

Bitwise OR of (7 | 4)
Explanation: On the basis of truth table of bitwise OR operator we can conclude that the result of
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
We used the similar concept of bitwise operator that are show in the image.
Implementation of OR operator:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a = 12, b = 25;
int result = a | b;
cout << result;
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int a = 12, b = 25;
int result = a | b;
System.out.println(result);
}
}
Python
a = 12
b = 25
result = a | b
print(result)
# This code is contributed by garg28harsh.
C#
using System;
public class GFG{
static public void Main (){
int a = 12, b = 25;
int result = a | b;
Console.WriteLine(result);
}
}
// This code is contributed by akashish__
JavaScript
let a = 12, b = 25;
let result = a | b;
document.write(result);
// This code is contributed by garg28harsh.
​Bitwise XOR Operator (^)
The ^ operator (also known as the XOR operator) stands for Exclusive Or. Here, if bits in the compared position do not match their resulting bit is 1. i.e, The result of the bitwise XOR operator is 1 if the corresponding bits of two operands are opposite, otherwise 0.
.png)
Example:
Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y

Bitwise OR of (7 ^ 4)
Explanation: On the basis of truth table of bitwise XOR operator we can conclude that the result of
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
We used the similar concept of bitwise operator that are show in the image.
Implementation of XOR operator:
C++
#include <iostream>
using namespace std;
int main()
{
int a = 12, b = 25;
cout << (a ^ b);
return 0;
}
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int a = 12, b = 25;
int result = a ^ b;
System.out.println(result);
}
}
// This code is contributed by garg28harsh.
Python
a = 12
b = 25
result = a ^ b
print(result)
# This code is contributed by garg28harsh.
C#
// C# Code
using System;
public class GFG {
static public void Main()
{
// Code
int a = 12, b = 25;
int result = a ^ b;
Console.WriteLine(result);
}
}
// This code is contributed by lokesh
JavaScript
let a = 12;
let b = 25;
console.log((a ^ b));
// This code is contributed by akashish__
Bitwise NOT Operator (!~)
All the above three bitwise operators are binary operators (i.e, requiring two operands in order to operate). Unlike other bitwise operators, this one requires only one operand to operate.
The bitwise Not Operator takes a single value and returns its one’s complement. The one’s complement of a binary number is obtained by toggling all bits in it, i.e, transforming the 0 bit to 1 and the 1 bit to 0.

Truth Table of Bitwise Operator NOT
Example:
Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT of X.

Explanation: On the basis of truth table of bitwise NOT operator we can conclude that the result of
~1 = 0
~0 = 1
We used the similar concept of bitwise operator that are show in the image.
Implementation of NOT operator:
C++
#include <iostream>
using namespace std;
int main()
{
int a = 0;
cout << "Value of a without using NOT operator: " << a;
cout << "\nInverting using NOT operator (with sign bit): " << (~a);
cout << "\nInverting using NOT operator (without sign bit): " << (!a);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int a = 0;
System.out.println(
"Value of a without using NOT operator: " + a);
System.out.println(
"Inverting using NOT operator (with sign bit): "
+ (~a));
if (a != 1)
System.out.println(
"Inverting using NOT operator (without sign bit): 1");
else
System.out.println(
"Inverting using NOT operator (without sign bit): 0");
}
}
// This code is contributed by lokesh.
Python
a = 0
print("Value of a without using NOT operator: " , a)
print("Inverting using NOT operator (with sign bit): " , (~a))
print("Inverting using NOT operator (without sign bit): " , int(not(a)))
# This code is contributed by akashish__
C#
using System;
public class GFG {
static public void Main()
{
int a = 0;
Console.WriteLine(
"Value of a without using NOT operator: " + a);
Console.WriteLine(
"Inverting using NOT operator (with sign bit): "
+ (~a));
if (a != 1)
Console.WriteLine(
"Inverting using NOT operator (without sign bit): 1");
else
Console.WriteLine(
"Inverting using NOT operator (without sign bit): 0");
}
}
// This code is contributed by akashish__
JavaScript
let a =0;
document.write("Value of a without using NOT operator: " + a);
document.write( "Inverting using NOT operator (with sign bit): " + (~a));
if(!a)
document.write( "Inverting using NOT operator (without sign bit): 1" );
else
document.write( "Inverting using NOT operator (without sign bit): 0" );
OutputValue of a without using NOT operator: 0
Inverting using NOT operator (with sign bit): -1
Inverting using NOT operator (without sign bit): 1
Left-Shift (<<)
The left shift operator is denoted by the double left arrow key (<<). The general syntax for left shift is shift-expression << k. The left-shift operator causes the bits in shift expression to be shifted to the left by the number of positions specified by k. The bit positions that the shift operation has vacated are zero-filled.
Note: Every time we shift a number towards the left by 1 bit it multiply that number by 2.

Logical left Shift
Example:
Input: Left shift of 5 by 1.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 1)

Left shift of 5 by 1
Output: 10
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010102, Which is equivalent to 10
Input: Left shift of 5 by 2.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 2)

Left shift of 5 by 2
Output: 20
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 101002, Which is equivalent to 20
Input: Left shift of 5 by 3.
Binary representation of 5 = 00101 and Left shift of 001012 by 1 (i.e, 00101 << 3)

Left shift of 5 by 3
Output: 40
Explanation: All bit of 5 will be shifted by 1 to left side and this result in 010002, Which is equivalent to 40
Implementation of Left shift operator:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
unsigned int num1 = 1024;
bitset<32> bt1(num1);
cout << bt1 << endl;
unsigned int num2 = num1 << 1;
bitset<32> bt2(num2);
cout << bt2 << endl;
unsigned int num3 = num1 << 2;
bitset<16> bitset13{ num3 };
cout << bitset13 << endl;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main(String[] args)
{
int num1 = 1024;
String bt1 = Integer.toBinaryString(num1);
bt1 = String.format("%32s", bt1).replace(' ', '0');
System.out.println(bt1);
int num2 = num1 << 1;
String bt2 = Integer.toBinaryString(num2);
bt2 = String.format("%32s", bt2).replace(' ', '0');
System.out.println(bt2);
int num3 = num1 << 2;
String bitset13 = Integer.toBinaryString(num3);
bitset13 = String.format("%16s", bitset13)
.replace(' ', '0');
System.out.println(bitset13);
}
}
// This code is contributed by akashish__
Python
# Python code for the above approach
num1 = 1024
bt1 = bin(num1)[2:].zfill(32)
print(bt1)
num2 = num1 << 1
bt2 = bin(num2)[2:].zfill(32)
print(bt2)
num3 = num1 << 2
bitset13 = bin(num3)[2:].zfill(16)
print(bitset13)
# This code is contributed by Prince Kumar
C#
using System;
class GFG {
public static void Main(string[] args)
{
int num1 = 1024;
string bt1 = Convert.ToString(num1, 2);
bt1 = bt1.PadLeft(32, '0');
Console.WriteLine(bt1);
int num2 = num1 << 1;
string bt2 = Convert.ToString(num2, 2);
bt2 = bt2.PadLeft(32, '0');
Console.WriteLine(bt2);
int num3 = num1 << 2;
string bitset13 = Convert.ToString(num3, 2);
bitset13 = bitset13.PadLeft(16, '0');
Console.WriteLine(bitset13);
}
}
// This code is contributed by akashish__
JavaScript
// JavaScript code for the above approach
let num1 = 1024;
let bt1 = num1.toString(2).padStart(32, '0');
console.log(bt1);
let num2 = num1 << 1;
let bt2 = num2.toString(2).padStart(32, '0');
console.log(bt2);
let num3 = num1 << 2;
let bitset13 = num3.toString(2).padStart(16, '0');
console.log(bitset13);
Output00000000000000000000010000000000
00000000000000000000100000000000
0001000000000000
Right-Shift (>>)
The right shift operator is denoted by the double right arrow key (>>). The general syntax for the right shift is “shift-expression >> k”. The right-shift operator causes the bits in shift expression to be shifted to the right by the number of positions specified by k. For unsigned numbers, the bit positions that the shift operation has vacated are zero-filled. For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used.
Note: Every time we shift a number towards the right by 1 bit it divides that number by 2.

Logical Right Shift
Example:
Input: Right shift of 5 by 1.
Binary representation of 5 = 00101 and Right shift of 00101 by 1 (i.e, 00101 >> 1)

Right shift of 5 by 1
Output: 2
Explanation: All bit of 5 will be shifted by 1 to Rightside and this result in 00010 Which is equivalent to 2
Input: Right shift of 5 by 2.
Binary representation of 5 = 00101 and Right shift of 00101 by 2 (i.e, 00101 >> 2)

Right shift of 5 by 2
Output: 1
Explanation: All bit of 5 will be shifted by 2 to Right side and this result in 00001, Which is equivalent to 1
Input: Right shift of 5 by 3.
Binary representation of 5 = 00101 and Right shift of 00101 by 3 (i.e, 00101 >> 3)

Right shift of 5 by 3
Output: 0
Explanation: All bit of 5 will be shifted by 3 to Right side and this result in 00000, Which is equivalent to 0
Implementation of Right shift operator:
C++
#include <bitset>
#include <iostream>
using namespace std;
int main()
{
unsigned int num1 = 1024;
bitset<32> bt1(num1);
cout << bt1 << endl;
unsigned int num2 = num1 >> 1;
bitset<32> bt2(num2);
cout << bt2 << endl;
unsigned int num3 = num1 >> 2;
bitset<16> bitset13{ num3 };
cout << bitset13 << endl;
}
JavaScript
// JavaScript code for the above approach
let num1 = 1024;
let bt1 = num1.toString(2).padStart(32, '0');
console.log(bt1);
let num2 = num1 >> 1;
let bt2 = num2.toString(2).padStart(32, '0');
console.log(bt2);
let num3 = num1 >> 2;
let bitset13 = num3.toString(2).padStart(16, '0');
console.log(bitset13);
// akashish__
Output00000000000000000000010000000000
00000000000000000000001000000000
0000000100000000
Application of Bit Operators
- Bit operations are used for the optimization of embedded systems.
- The Exclusive-or operator can be used to confirm the integrity of a file, making sure it has not been corrupted, especially after it has been in transit.
- Bitwise operations are used in Data encryption and compression.
- Bits are used in the area of networking, framing the packets of numerous bits which are sent to another system generally through any type of serial interface.
- Digital Image Processors use bitwise operations to enhance image pixels and to extract different sections of a microscopic image.
Important Practice Problems on Bitwise Algorithm:
If we want to set a bit at nth position in the number ‘num’, it can be done using the ‘OR’ operator( | ).
- First, we left shift 1 to n position via (1<<n)
- Then, use the “OR” operator to set the bit at that position. “OR” operator is used because it will set the bit even if the bit is unset previously in the binary representation of the number ‘num’.
Note: If the bit would be already set then it would remain unchanged.
Below is the implementation:
C++
#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;
}
Java
/*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.
Python
# 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
C#
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
JavaScript
<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>
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.
- First, we left shift ‘1’ to n position via (1<<n) then we use bitwise NOT operator ‘~’ to unset this shifted ‘1’.
- Now after clearing this left shifted ‘1’ i.e making it to ‘0’ we will ‘AND'(&) with the number ‘num’ that will unset bit at nth position.
Below is the implementation:
C++
#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;
}
Java
/*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;
}
}
Python
# 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)
C#
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);
}
}
JavaScript
// 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
return num &= (~(1 << pos));
}
let num = 7;
let pos = 1;
console.log(unset(num, pos));
// contributed by akashish__
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.
- Properties of ‘XOR’ operator.
- 1^1 = 0
- 0^0 = 0
- 1^0 = 1
- 0^1 = 1
- If two bits are different then the ‘XOR’ operator returns a set bit(1) else it returns an unset bit(0).
Below is the implementation:
C++
#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;
}
Java
/*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.
Python
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
C#
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
JavaScript
// First step is to shift 1,Second step is to XOR with given
// number
function toggle(num, pos){
// First Step: Shifts '1'
// Second Step: XOR num
num ^= (1 << pos)
console.log(num)
}
let num = 4;
let pos = 1;
toggle(num, pos);
// contributed by akashish__
Time Complexity: O(1)
Auxiliary Space: O(1)
We used the left shift (<<) operation on 1 to shift the bits to nth position and then use the & operation with number given number, and check if it is not-equals to 0.
Below is the implementation:
C++
#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 = 2;
bool bit = at_position(num, pos);
cout << bit << endl;
return 0;
}
Java
/*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;
}
}
Python
# code
def at_position(num, pos):
bit = num & (1 << pos)
return bit
num = 5
pos = 0
bit = at_position(num, pos)
print(bit)
C#
using System;
public class GFG {
public static bool at_position(int num, int pos)
{
int bit = num & (1 << pos);
if (bit == 0)
return false;
return true;
}
static public void Main()
{
int num = 5;
int pos = 2;
bool bit = at_position(num, pos);
Console.WriteLine(bit);
}
}
// This code is contributed by akashish__
JavaScript
<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>
Below is the implementation:
C++
#include <iostream>
using namespace std;
int main()
{
int num = 12;
int ans = num << 1;
cout << ans << endl;
return 0;
}
Java
/*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.
Python
# Python program for the above approach
num = 12
ans = num << 1
print(ans)
# This code is contributed by Shubham Singh
C#
using System;
public class GFG {
static public void Main()
{
int num = 12;
Console.WriteLine(num << 1);
}
}
// This code is contributed by sarajadhav12052009
JavaScript
<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>
6. Divide a number 2 using the right shift operator
Below is the implementation:
C++
#include <iostream>
using namespace std;
int main()
{
int num = 12;
int ans = num >> 1;
cout << ans << endl;
return 0;
}
Java
/*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.
Python
# Python program for the above approach
num = 12
ans = num >> 1
print(ans)
# This code is contributed by Shubham Singh
C#
using System;
public class GFG {
static public void Main()
{
int num = 12;
Console.WriteLine(num >> 1);
}
}
// This code is contributed by sarajadhav12052009
JavaScript
<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>
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.
C++
// 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
# 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
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)
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.
Below is the implementation of the above approach.
C++
// 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
// Function to check if x is power of 2
public static 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);
}
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)));
}
// contributed by akashish__
Time Complexity: O(1)
Auxiliary Space: O(1)
Counting set bits means, counting total number of 1’s in the binary representation of an integer. For this problem we go through all the bits of given number and check whether it is set or not by performing AND operation (with 1).
Below is the implementation:
C++
// Function to calculate the number of set bits.
int countBits(int n)
{
// Initialising a variable count to 0.
int count = 0;
while (n) {
// If the last bit is 1, count will be incremented
// by 1 in this step.
count += n & 1;
// Using the right shift operator.
// The bits will be shifted one position to the
// right.
n >>= 1;
}
return count;
}
Java
// Function to calculate the number of set bits.
public static int countBits(int n)
{
// Initialising a variable count to 0.
int count = 0;
while (n > 0) {
// If the last bit is 1, count will be incremented
// by 1 in this step.
count += n & 1;
// Using the right shift operator.
// The bits will be shifted one position to the
// right.
n >>= 1;
}
return count;
}
Python
def countBits(n):
# Initializing a variable count to 0
count = 0
while n:
# If the last bit is 1, count will be incremented by 1 in this step.
count += n & 1
# Using the right shift operator. The bits will be shifted one position to the right.
n >>= 1
return count
C#
using System;
public class GFG {
// Function to calculate the number of set bits.
public static int countBits(int n)
{
// Initialising a variable count to 0.
int count = 0;
while (n > 0)
{
// If the last bit is 1, count will be
// incremented by 1 in this step.
count += n & 1;
// Using the right shift operator.
// The bits will be shifted one position to the
// right.
n >>= 1;
}
return count;
}
static public void Main() {}
}
// This code is contributed by akashish__
JavaScript
// Function to calculate the number of set bits.
function countBits(n)
{
// Initialising a variable count to 0.
let count = 0;
while (n) {
// If the last bit is 1, count will be incremented
// by 1 in this step.
count += n & 1;
// Using the right shift operator.
// The bits will be shifted one position to the
// right.
n >>= 1;
}
return count;
}
The idea is to unset the rightmost bit of number n and XOR the result with n. Then the rightmost set bit in n will be the position of the only set bit in the result. Note that if n is odd, we can directly return 1 as the first bit is always set for odd numbers.
Example:
The number 20 in binary is 00010100, and the position of the rightmost set bit is 3.
00010100 & (n = 20)
00010011 (n-1 = 19)
——————-
00010000 ^ (XOR result number with n)
00010100
——————-
00000100 ——-> rightmost set bit will tell us the position
Below is the implementation:
C++
// Returns the position of the rightmost set bit of `n`
int positionOfRightmostSetBit(int n)
{
// if the number is odd, return 1
if (n & 1) {
return 1;
}
// unset rightmost bit and xor with the number itself
n = n ^ (n & (n - 1));
// find the position of the only set bit in the result;
// we can directly return `log2(n) + 1` from the
// function
int pos = 0;
while (n) {
n = n >> 1;
pos++;
}
return pos;
}
Java
// Returns the position of the rightmost set bit of `n`
public static int positionOfRightmostSetBit(int n)
{
// if the number is odd, return 1
if ((n & 1) != 0) {
return 1;
}
// unset rightmost bit and xor with the number itself
n = n ^ (n & (n - 1));
// find the position of the only set bit in the result;
// we can directly return `log2(n) + 1` from the
// function
int pos = 0;
while (n != 0) {
n = n >> 1;
pos++;
}
return pos;
}
Python
# Returns the position of the rightmost set bit of `n`
def positionOfRightmostSetBit(n):
# if the number is odd, return 1
if n & 1:
return 1
# unset rightmost bit and xor with the number itself
n = n ^ (n & (n - 1))
# find the position of the only set bit in the result;
# we can directly return `log2(n) + 1` from the function
pos = 0
while n:
n = n >> 1
pos = pos + 1
return pos
C#
// Returns the position of the rightmost set bit of `n`
public static int positionOfRightmostSetBit(int n)
{
// if the number is odd, return 1
if ((n & 1) != 0) {
return 1;
}
// unset rightmost bit and xor with the number itself
n = n ^ (n & (n - 1));
// find the position of the only set bit in the result;
// we can directly return `log2(n) + 1` from the
// function
int pos = 0;
while (n != 0) {
n = n >> 1;
pos++;
}
return pos;
}
JavaScript
// Returns the position of the rightmost set bit of `n`
function positionOfRightmostSetBit( n)
{
// if the number is odd, return 1
if (n & 1) {
return 1;
}
// unset rightmost bit and xor with the number itself
n = n ^ (n & (n - 1));
// find the position of the only set bit in the result;
// we can directly return `log2(n) + 1` from the
// function
let pos = 0;
while (n) {
n = n >> 1;
pos++;
}
return pos;
}
Similar Reads
Bitwise Algorithms
Bitwise 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 Algori
4 min read
Introduction to Bitwise Algorithms - Data Structures and Algorithms Tutorial
Bit stands for binary digit. A bit is the basic unit of information and can only have one of two possible values that is 0 or 1. In our world, we usually with numbers using the decimal base. In other words. we use the digit 0 to 9 However, there are other number representations that can be quite use
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if bot
7 min read
Bitwise Operators in Java
In Java, Operators are special symbols that perform specific operations on one or more than one operands. They build the foundation for any type of calculation or logic in programming. There are so many operators in Java, among all, bitwise operators are used to perform operations at the bit level.
6 min read
Python Bitwise Operators
Python bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned in decimal format. Note: Python bitwi
6 min read
JavaScript Bitwise Operators
In JavaScript, a number is stored as a 64-bit floating-point number but bitwise operations are performed on a 32-bit binary number. To perform a bit-operation, JavaScript converts the number into a 32-bit binary number (signed) and performs the operation and converts back the result to a 64-bit numb
5 min read
All about Bit Manipulation
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 implementa
14 min read
What is Endianness? Big-Endian & Little-Endian
Computers operate using binary code, a language made up of 0s and 1s. This binary code forms the foundation of all computer operations, enabling everything from rendering videos to processing complex algorithms. A single bit is a 0 or a 1, and eight bits make up a byte. While some data, such as cert
5 min read
Bits manipulation (Important tactics)
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^xHow to know if a number is a power of 2?Find XOR of all
15+ min read
Easy Problems on Bit Manipulations and Bitwise Algorithms
Binary representation of a given number
Given an integer n, the task is to print the binary representation of the number. Note: The given number will be maximum of 32 bits, so append 0's to the left if the result string is smaller than 30 length. Examples: Input: n = 2Output: 00000000000000000000000000000010 Input: n = 0Output: 0000000000
6 min read
Count set bits in an integer
Write an efficient program to count the number of 1s in the binary representation of an integer.Examples : Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bits Input : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits [Naive Approach] - One by One Counting
15+ min read
Add two bit strings
Given two binary strings s1 and s2 consisting of only 0s and 1s. Find the resultant string after adding the two Binary Strings.Note: The input strings may contain leading zeros but the output string should not have any leading zeros. Examples: Input: s1 = "1101", s2 = "111"Output: 10100Explanation:
2 min read
Turn off the rightmost set bit
Given an integer n, turn remove turn off the rightmost set bit in it. Input: 12Output: 8Explanation : Binary representation of 12 is 00...01100. If we turn of the rightmost set bit, we get 00...01000 which is binary representation of 8 Input: 7 Output: 6 Explanation : Binary representation for 7 is
7 min read
Rotate bits of a number
Given a 32-bit integer n and an integer d, rotate the binary representation of n by d positions in both left and right directions. After each rotation, convert the result back to its decimal representation and return both values in an array as [left rotation, right rotation].Note: A rotation (or cir
7 min read
Compute modulus division by a power-of-2-number
Given two numbers n and d where d is a power of 2 number, the task is to perform n modulo d without the division and modulo operators. Input: 6 4Output: 2 Explanation: As 6%4 = 2Input: 12 8Output: 4Explanation: As 12%8 = 4Input: 10 2Output: 0Explanation: As 10%2 = 0 Approach: The idea is to leverage
3 min read
Find the Number Occurring Odd Number of Times
Given an array of positive integers. All numbers occur an even number of times except one number which occurs an odd number of times. Find the number in O(n) time & constant space. Examples : Input : arr = {1, 2, 3, 2, 3, 1, 3}Output : 3 Input : arr = {5, 7, 2, 7, 5, 2, 5}Output : 5 Recommended
12 min read
Program to find whether a given number is power of 2
Given a positive integer n, the task is to find if it is a power of 2 or not. Examples: Input : n = 16Output : YesExplanation: 24 = 16 Input : n = 42Output : NoExplanation: 42 is not a power of 2 Input : n = 1Output : YesExplanation: 20 = 1 Approach 1: Using Log - O(1) time and O(1) spaceThe idea is
12 min read
Find position of the only set bit
Given a number n containing only 1 set bit in its binary representation, the task is to find the position of the only set bit. If there are 0 or more than 1 set bits, then return -1. Note: Position of set bit '1' should be counted starting with 1 from the LSB side in the binary representation of the
8 min read
Check for Integer Overflow
Given two integers a and b. The task is to design a function that adds two integers and detects overflow during the addition. If the sum does not cause an overflow, return their sum. Otherwise, return -1 to indicate an overflow.Note: You cannot use type casting to a larger data type to check for ove
7 min read
Find XOR of two number without using XOR operator
Given two integers, the task is to find XOR of them without using the XOR operator. Examples : Input: x = 1, y = 2Output: 3 Input: x = 3, y = 5Output: 6 Approach - Checking each bit - O(log n) time and O(1) spaceA Simple Solution is to traverse all bits one by one. For every pair of bits, check if b
9 min read
Check if two numbers are equal without using arithmetic and comparison operators
Given two numbers, the task is to check if two numbers are equal without using Arithmetic and Comparison Operators or String functions. Method 1 : The idea is to use XOR operator. XOR of two numbers is 0 if the numbers are the same, otherwise non-zero. C/C++ Code // C++ program to check if two numbe
8 min read
Detect if two integers have opposite signs
Given two integers a and b, the task is to determine whether they have opposite signs. Return true if the signs of the two numbers are different and false otherwise. Examples: Input: a = -5, b = 10Output: trueExplanation: One number is negative and the other is positive, so their signs are different
9 min read
Swap Two Numbers Without Using Third Variable
Given two variables a and y, swap two variables without using a third variable. Examples: Input: a = 2, b = 3Output: a = 3, b = 2 Input: a = 20, b = 0Output: a = 0, b = 20 Input: a = 10, b = 10Output: a = 10, b = 10 Table of Content Using Arithmetic OperatorsUsing Bitwise XORBuilt-in SwapUsing Arith
6 min read
Russian Peasant (Multiply two numbers using bitwise operators)
Given two integers a and b, the task is to multiply them without using the multiplication operator. Instead of that, use the Russian Peasant Algorithm. Examples: Input: a = 2, b = 5Output: 10Explanation: Product of 2 and 5 is 10. Input: a = 6, b = 9Output: 54Explanation: Product of 6 and 9 is 54. In
4 min read