The Wayback Machine - https://web.archive.org/web/20241127044359/https://www.geeksforgeeks.org/bits-manipulation-important-tactics/
Open In App

Bits manipulation (Important tactics)

Last Updated : 07 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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));

Output
1

Refer Equal Sum and XOR for details.

Time complexity: O(log n)

Auxiliary Space: O(1)

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

This can be solved based on the following fact:

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

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

Below is the implementation of the above approach.

CPP
//  Function to check if x is power of 2
bool isPowerOfTwo(int x)
{
     // First x in the below expression is
     // for  the case when x is 0 
     return x && (!(x & (x - 1)));
}
Java
/*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);

Output
3

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

7. The Quickest way to swap two numbers:

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

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

C++
#include <iostream>
using namespace std;

int main()
{
    int a = 5;
      int b = 7;
      cout<<"Before Swapping, a = "<<a<<" "<<"b = "<<b<<endl;
    a ^= b;
    b ^= a;
    a ^= b;
      cout<<"After Swapping, a = "<<a<<" "<<"b = "<<b<<endl;
    return 0;
}

// This code is contributed by akashish__
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;

class GFG {
  public static void main(String[] args)
  {
    int a = 5;
    int b = 7;
    System.out.print("Before Swapping, a = ");
    System.out.print(a);
    System.out.print(" ");
    System.out.print("b = ");
    System.out.print(b);
    System.out.println("");
    a ^= b;
    b ^= a;
    a ^= b;
    System.out.print("After Swapping, a = ");
    System.out.print(a);
    System.out.print(" ");
    System.out.print("b = ");
    System.out.print(b);
  }
}

// This code is contributed by akashish__
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__

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

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

Refer swap two numbers for more details.  

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

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

C++
int setBitNumber(int n)
{
    // Below steps set bits after
    // MSB (including MSB)

    // Suppose n is 273 (binary
    // is 100010001). It does following
    // 100010001 | 010001000 = 110011001
    n |= n >> 1;

    // This makes sure 4 bits
    // (From MSB and including MSB)
    // are set. It does following
    // 110011001 | 001100110 = 111111111
    n |= n >> 2;

    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;

    // Increment n by 1 so that
    // there is only one set bit
    // which is just before original
    // MSB. n now becomes 1000000000
    n = n + 1;

    // Return original MSB after shifting.
    // n now becomes 100000000
    return (n >> 1);
}
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {

  public static int setBitNumber(int n)
  {
    // Below steps set bits after
    // MSB (including MSB)

    // Suppose n is 273 (binary
    // is 100010001). It does following
    // 100010001 | 010001000 = 110011001
    n |= n >> 1;

    // This makes sure 4 bits
    // (From MSB and including MSB)
    // are set. It does following
    // 110011001 | 001100110 = 111111111
    n |= n >> 2;

    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;

    // Increment n by 1 so that
    // there is only one set bit
    // which is just before original
    // MSB. n now becomes 1000000000
    n = n + 1;

    // Return original MSB after shifting.
    // n now becomes 100000000
    return (n >> 1);
  }


  public static void main (String[] args) {
  }
}

// This code is contributed by akashish__
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

DSA Self Paced Course




Previous Article
Next Article

Similar Reads

Toggle bits of a number except first and last bits
Given a number, the task is to toggle bits of the number except the first and the last bit.Examples: Input : 10 Output : 12 Binary representation:- 1 0 1 0 After toggling first and last : 1 1 0 0 Input : 9 Output : 15 Binary representation : 1 0 0 1 After toggling first and last : 1 1 1 1 Prerequisite: Find most significant set bit of a number Gene
8 min read
Check if all bits can be made same by flipping two consecutive bits
Given a binary string, the task is to find whether all the digits of the string can be made equal i.e either 0 or 1 by flipping two consecutive bits any number of times.Examples: Input: 01011Output: YESExplanation:Flip 2nd and 3rd bit -> 00111, again flipping 1'st and 2'nd bit -> 11111 Input: 100011Output: NOExplanation:No number of moves can
5 min read
Flip bits of the sum of count of set bits of two given numbers
Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representation of the sum obtained = 101Flipping the bits of th
5 min read
Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most N/2. Examples: Input: S = "1010001"Output: 3Expla
12 min read
Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X & Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X & Y) = M, where ⊕ denotes the Bitwise XOR and & denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n > 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Print numbers having first and last bits as the only set bits
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.Examples: Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2 Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i. C
10 min read
Array Manipulation and Sum
Given an array arr[] of N integers and an integer S. The task is to find an element K in the array such that if all the elements from the array > K are made equal to K then the sum of all the elements of the resultant array becomes equal to S. If it is not possible to find such an element then print -1 . Examples: Input: M = 15, arr[] = {12, 3,
5 min read
Mutation Algorithms for String Manipulation (GA)
Genetic Algorithms(GAs) are adaptive heuristic search algorithms that belong to the larger part of evolutionary algorithms. In each generation chromosomes(our solution candidates) undergo mutation and crossover and then selection to produce a better population whose candidates are nearer to our desired solution. Mutation Operator is a unary operato
2 min read
Maximize the Expression | Bit Manipulation
Given two positive integers A and B. Let's define D such that B AND D = D. The task is to maximize the expression A XOR D.Examples: Input: A = 11 B = 4 Output: 15 Take D = 4 as (B AND D) = (4 AND 4) = 4. Also, (A XOR D) = (11 XOR 4) = 15 which is the maximum according to the given condition. Input: A = 9 and B = 13 Output: 13 Naive approach: Since
7 min read
Maximize the expression (A AND X) * (B AND X) | Bit Manipulation
Given two positive integers A and B such that A != B, the task is to find a positive integer X which maximizes the expression (A AND X) * (B AND X).Example: Input: A = 9 B = 8 Output: 8 (9 AND 8) * (8 AND 8) = 8 * 8 = 64 (maximum possible)Input: A = 11 and B = 13 Output: 9 Naive approach: One can run a loop from 1 to max(A, B) and can easily find X
6 min read
Winner in the Rock-Paper-Scissor game using Bit manipulation
Two players are playing a series of games of Rock–paper–scissors. There are a total of N games played represented by an array arr[][] where arr[i][0] is the move of player one and arr[i][1] is the move of the player two in the ith game from the set {'R', 'P', 'S'}. The task is to find the winner of each of the game. Note that the game is a draw if
6 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 implementation fast. Below are the Bitwise Operators that ar
14 min read
Find square root of a number using Bit Manipulation
Given a non-negative integer N, the task is to find the square root of N using bitwise operations. If the integer is not the perfect square, return largest integer that is smaller than or equal to square root of N i.e., floor(√N). Examples: Input: N = 36Output: 6Explanation: The square root of 36 is 6. Input: N = 19Output: 4Explanation: The square
7 min read
Store two numbers in one Byte using Bit manipulation
Given two values A and B (A, B < 16), the task is to store the numbers in one byte. Examples: Input: A = 5, B = 9Output: 89Explanation: 5 in binary form is 0101 and the binary form for 9 is 1001. Since 1 byte contains 8 bits, we can store these two nibbles in that 1 bit, forming 01011001 which when converted into decimal becomes 89. Input: A = 2
8 min read
What is Bit Manipulation
Bit manipulation is the process of manipulating individual bits or groups of bits in a binary representation of data. It involves performing logical and arithmetic operations on binary digits or bits to achieve a desired result. How to Perform Bit Manipulation?Bit manipulation is performed using bit-wise operators, which operate on individual bits
4 min read
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can. Boolean arrays have been
10 min read
String Comparison and Manipulation Queries with Blocking and Swapping
Given Two strings S1 and S2 of equal length N, consisting of lowercase letters. There are also given integer T and Q queries. Each query can be one of three types, for queries of the first and second types, the specified positions and characters are not blocked. The task for this problem is to print the answer for query type 3. Type 1: {1, pos} Blo
15+ min read
String manipulation and Kth lexicographically largest character query
Given a string s whose length is n and array queries of length q where each element of queries is either of type 1 query or type 2 query, the task is to perform each query in the same order as given in queries and return an array res such that the res array contains the answer for each type2 query in the same order as it appeared in queries that ar
15+ min read
Print all Palindromic Partitions of a String using Bit Manipulation
Given a string, find all possible palindromic partitions of a given string. Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions. Example: Input: nitinOutput: n i t i n n iti n nitin Input: geeksOutput: g
10 min read
Bit Manipulation for Competitive Programming
Bit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usage. Table of Content Bitwise OperatorsUseful Bitwis
15+ min read
Matrix manipulation in Python
In python matrix can be implemented as 2D list or 2D Array. Forming matrix from latter, gives the additional functionalities for performing various operations in matrix. These operations and array are defines in module "numpy". Operation on Matrix : 1. add() :- This function is used to perform element wise matrix addition. 2. subtract() :- This fun
4 min read
String Manipulation Techniques
Recent articles on String ! Word Wrap problem ( Space optimized solution ) Form minimum number from given sequence Maximum number of characters between any two same character in a string Print shortest path to print a string on screen Minimum number of stops from given path Check whether second string can be formed from characters of first string M
6 min read
Toggle all the bits of a number except k-th bit.
Given a positive (or unsigned) integer n, write a function to toggle all the bits except k-th bit. Here value of k starts from 0 (zero) and from right. Examples: Input : n = 4294967295, k = 0 Output : 1 The number 4294967295 in 32 bits has all bits set. When we toggle all bits except last bit, we get 1. Input : n = 1, k = 1 Output : 4294967292 4294
4 min read
Reverse bits of a positive integer number in Python
Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this problem quickly in Python. Approach is very simple,
4 min read
Smallest number whose set bits are maximum in a given range
Given a positive integer 'l' and 'r'. Find the smallest number 'n' such that l <= n <= r and count of the number of set bits(number of '1's in binary representation) is as maximum as possible. Examples : Input: 1 4Output: 3Explanation:Binary representation from '1' to '4':110 = 0012210 = 0102310 = 0112110 = 1002Thus number '3' has maximum set
9 min read
Unset the last m bits
Given a non-negative number n. The problem is to unset the last m bits in the binary representation of n.Constraint: 1 <= m <= num, where num is the number of bits in the binary representation of n. Examples: Input : n = 10, m = 2 Output : 8 (10)10 = (1010)2 (8)10 = (1000)2 The last two bits in the binary representation of 10 have been unset.
6 min read
Reverse bits using lookup table in O(1) time
Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Examples: Input : n = 1 Output : 2147483648 On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648 Output : 1 In the previous post we had seen two method that solved this problem in O(n) & O(logn ) time. Her
7 min read
Count set bits using Python List comprehension
Write an efficient program to count number of 1s in binary representation of an integer. Examples: Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 11 Output : 3 Binary representation of 11 is 1101 and has 3 set bits We have existing solution for this problem please refer Count set bits in an integer link. W
2 min read
Python map function | Count total set bits in all numbers from 1 to n
Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n. Examples: Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 We have existing solution for t
2 min read
Practice Tags :
three90RightbarBannerImg