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
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
import java.io.*;
class GFG
{
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) {
}
}
|
Python3
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
|
C#
using System;
public class GFG
{
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(){}
}
|
Javascript
<script>
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;
}
</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++
#include <bits/stdc++.h>
using namespace std;
int countValues( int n)
{
int unset_bits=0;
while (n)
{
if ((n & 1) == 0)
unset_bits++;
n=n>>1;
}
return 1 << unset_bits;
}
int main()
{
int n = 15;
cout << countValues(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
public static int countValues( int n)
{
int unset_bits = 0 ;
while (n > 0 )
{
if ((n & 1 ) == 0 )
unset_bits++;
n = n>> 1 ;
}
return 1 << unset_bits;
}
public static void main (String[] args) {
int n = 15 ;
System.out.print(countValues(n));
}
}
|
Python3
def countValues(n):
unset_bits = 0
while (n):
if ((n & 1 ) = = 0 ):
unset_bits + = 1
n = n>> 1
return 1 << unset_bits
n = 15
print (countValues(n))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int countValues( int n)
{
int unset_bits = 0;
while (n > 0)
{
if ((n & 1) == 0)
unset_bits++;
n = n>>1;
}
return 1 << unset_bits;
}
public static void Main()
{
int n = 15;
Console.Write(countValues(n));
}
}
|
Javascript
function countValues(n)
{
let unset_bits=0;
while (n)
{
if ((n & 1) == 0)
unset_bits++;
n=n>>1;
}
return 1 << unset_bits;
}
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
bool isPowerOfTwo( int x)
{
return x && (!(x & (x - 1)));
}
|
Java
import java.io.*;
class GFG {
static public boolean isPowerOfTwo( int x)
{
return (x != 0 ) && ((x & (x - 1 )) == 0 );
}
public static void main (String[] args) {
}
}
|
Python3
def isPowerOfTwo(x):
return x and ( not (x & (x - 1 )))
|
C#
using System;
public class GFG{
static public bool isPowerOfTwo( int x)
{
return (x != 0) && ((x & (x - 1)) == 0);
}
static public void Main (){
}
}
|
Javascript
function isPowerOfTwo(x)
{
return x && (!(x & (x - 1)));
}
|
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
#include <iostream>
using namespace std;
int main()
{
auto number = 0b011;
cout << number;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
int number = 0b011;
System.out.println(number);
}
}
|
Python3
number = 0b011
print (number)
|
C#
using System;
public class GFG {
static public void Main()
{
int number = 0b011;
Console.WriteLine(number);
}
}
|
Javascript
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;
}
|
Java
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);
}
}
|
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)
|
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);
}
}
|
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);
|
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)
{
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n = n + 1;
return (n >> 1);
}
|
Java
import java.io.*;
class GFG {
public static int setBitNumber( int n)
{
n |= n >> 1 ;
n |= n >> 2 ;
n |= n >> 4 ;
n |= n >> 8 ;
n |= n >> 16 ;
n = n + 1 ;
return (n >> 1 );
}
public static void main (String[] args) {
}
}
|
Python3
def setBitNumber(n):
n | = n >> 1
n | = n >> 2
n | = n >> 4
n | = n >> 8
n | = n >> 16
n = n + 1
return (n >> 1 )
|
C#
using System;
public class GFG{
public static int setBitNumber( int n)
{
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n = n + 1;
return (n >> 1);
}
static public void Main (){
}
}
|
Javascript
function setBitNumber(n)
{
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n = n + 1;
return (n >> 1);
}
|
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++
static bool allBitsAreSet( int n)
{
if (((n + 1) & n) == 0)
return true ;
return false ;
}
bool bitsAreInAltOrder(unsigned int n)
{
unsigned int num = n ^ (n >> 1);
return allBitsAreSet(num);
}
|
Java
import java.io.*;
class GFG {
public static boolean allBitsAreSet( long n)
{
if (((n + 1 ) & n) == 0 )
return true ;
return false ;
}
public static boolean bitsAreInAltOrder( long n)
{
long num = n ^ (n >> 1 );
return allBitsAreSet(num);
}
public static void main (String[] args) {
}
}
|
Python3
def allBitsAreSet(n):
if (((n + 1 ) & n) = = 0 ):
return True
return False
def bitsAreInAltOrder(n):
num = n ^ (n >> 1 )
return allBitsAreSet(num)
|
C#
using System;
public class GFG
{
public static bool allBitsAreSet( uint n)
{
if (((n + 1) & n) == 0)
return true ;
return false ;
}
public static bool bitsAreInAltOrder( uint n)
{
uint num = n ^ (n >> 1);
return allBitsAreSet(num);
}
static public void Main() {}
}
|
Javascript
function allBitsAreSet(n)
{
if (((n + 1) & n) == 0)
return true ;
return false ;
}
function bitsAreInAltOrder(n)
{
let num = n ^ (n >> 1);
return allBitsAreSet(num);
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Refer check if a number has bits in alternate pattern for details.

DSA Self Paced Course
If you like GeeksforGeeks 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 GeeksforGeeks 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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
10 Jul, 2023
Like Article
Save Article