The Wayback Machine - https://web.archive.org/web/20240927021739/https://www.geeksforgeeks.org/generate-n-bit-gray-codes/
Open In App

Generate n-bit Gray Codes

Last Updated : 03 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a number N, generate bit patterns from 0 to 2^N-1 such that successive patterns differ by one bit.

Examples:

Input: N = 2
Output: 00 01 11 10

Input: N = 3
Output: 000 001 011 010 110 111 101 100
 

Method-1

The above sequences are Gray Codes of different widths. Following is an interesting pattern in Gray Codes.
n-bit Gray Codes can be generated from list of (n-1)-bit Gray codes using following steps.

  1. Let the list of (n-1)-bit Gray codes be L1. Create another list L2 which is reverse of L1.
  2. Modify the list L1 by prefixing a ‘0’ in all codes of L1.
  3. Modify the list L2 by prefixing a ‘1’ in all codes of L2.
  4. Concatenate L1 and L2. The concatenated list is required list of n-bit Gray codes

For example, following are steps for generating the 3-bit Gray code list from the list of 2-bit Gray code list. L1 = {00, 01, 11, 10} (List of 2-bit Gray Codes) L2 = {10, 11, 01, 00} (Reverse of L1) Prefix all entries of L1 with ‘0’, L1 becomes {000, 001, 011, 010} Prefix all entries of L2 with ‘1’, L2 becomes {110, 111, 101, 100} Concatenate L1 and L2, we get {000, 001, 011, 010, 110, 111, 101, 100} To generate n-bit Gray codes, we start from list of 1 bit Gray codes. The list of 1 bit Gray code is {0, 1}. We repeat above steps to generate 2 bit Gray codes from 1 bit Gray codes, then 3-bit Gray codes from 2-bit Gray codes till the number of bits becomes equal to n.

Below is the implementation of the above approach:

C++




// C++ program to generate n-bit Gray codes
#include <iostream>
#include <string>
#include <vector>
using namespace std;
 
// This function generates all n bit Gray codes and prints the
// generated codes
void generateGrayarr(int n)
{
    // base case
    if (n <= 0)
        return;
 
    // 'arr' will store all generated codes
    vector<string> arr;
 
    // start with one-bit pattern
    arr.push_back("0");
    arr.push_back("1");
 
    // Every iteration of this loop generates 2*i codes from previously
    // generated i codes.
    int i, j;
    for (i = 2; i < (1<<n); i = i<<1)
    {
        // Enter the previously generated codes again in arr[] in reverse
        // order. Nor arr[] has double number of codes.
        for (j = i-1 ; j >= 0 ; j--)
            arr.push_back(arr[j]);
 
        // append 0 to the first half
        for (j = 0 ; j < i ; j++)
            arr[j] = "0" + arr[j];
 
        // append 1 to the second half
        for (j = i ; j < 2*i ; j++)
            arr[j] = "1" + arr[j];
    }
 
    // print contents of arr[]
    for (i = 0 ; i < arr.size() ; i++ )
        cout << arr[i] << endl;
}
 
// Driver program to test above function
int main()
{
    generateGrayarr(3);
    return 0;
}


Java




// Java program to generate n-bit Gray codes
import java.util.*;
class GfG {
 
// This function generates all n bit Gray codes and prints the
// generated codes
static void generateGrayarr(int n)
{
    // base case
    if (n <= 0)
        return;
 
    // 'arr' will store all generated codes
    ArrayList<String> arr = new ArrayList<String> ();
 
    // start with one-bit pattern
    arr.add("0");
    arr.add("1");
 
    // Every iteration of this loop generates 2*i codes from previously
    // generated i codes.
    int i, j;
    for (i = 2; i < (1<<n); i = i<<1)
    {
        // Enter the previously generated codes again in arr[] in reverse
        // order. Nor arr[] has double number of codes.
        for (j = i-1 ; j >= 0 ; j--)
            arr.add(arr.get(j));
 
        // append 0 to the first half
        for (j = 0 ; j < i ; j++)
            arr.set(j, "0" + arr.get(j));
 
        // append 1 to the second half
        for (j = i ; j < 2*i ; j++)
            arr.set(j, "1" + arr.get(j));
    }
 
    // print contents of arr[]
    for (i = 0 ; i < arr.size() ; i++ )
        System.out.println(arr.get(i));
}
 
// Driver program to test above function
public static void main(String[] args)
{
    generateGrayarr(3);
}
}


Python3




# Python3 program to generate n-bit Gray codes
import math as mt
 
# This function generates all n bit Gray
# codes and prints the generated codes
def generateGrayarr(n):
 
    # base case
    if (n <= 0):
        return
 
    # 'arr' will store all generated codes
    arr = list()
 
    # start with one-bit pattern
    arr.append("0")
    arr.append("1")
 
    # Every iteration of this loop generates
    # 2*i codes from previously generated i codes.
    i = 2
    j = 0
    while(True):
 
        if i >= 1 << n:
            break
     
        # Enter the previously generated codes
        # again in arr[] in reverse order.
        # Nor arr[] has double number of codes.
        for j in range(i - 1, -1, -1):
            arr.append(arr[j])
 
        # append 0 to the first half
        for j in range(i):
            arr[j] = "0" + arr[j]
 
        # append 1 to the second half
        for j in range(i, 2 * i):
            arr[j] = "1" + arr[j]
        i = i << 1
 
    # print contents of arr[]
    for i in range(len(arr)):
        print(arr[i])
 
# Driver Code
generateGrayarr(3)
 
# This code is contributed
# by Mohit kumar 29


C#




using System;
using System.Collections.Generic;
 
// C# program to generate n-bit Gray codes 
public class GfG
{
 
// This function generates all n bit Gray codes and prints the 
// generated codes 
public static void generateGrayarr(int n)
{
    // base case 
    if (n <= 0)
    {
        return;
    }
 
    // 'arr' will store all generated codes 
    List<string> arr = new List<string> ();
 
    // start with one-bit pattern 
    arr.Add("0");
    arr.Add("1");
 
    // Every iteration of this loop generates 2*i codes from previously 
    // generated i codes. 
    int i, j;
    for (i = 2; i < (1 << n); i = i << 1)
    {
        // Enter the previously generated codes again in arr[] in reverse 
        // order. Nor arr[] has double number of codes. 
        for (j = i - 1 ; j >= 0 ; j--)
        {
            arr.Add(arr[j]);
        }
 
        // append 0 to the first half 
        for (j = 0 ; j < i ; j++)
        {
            arr[j] = "0" + arr[j];
        }
 
        // append 1 to the second half 
        for (j = i ; j < 2 * i ; j++)
        {
            arr[j] = "1" + arr[j];
        }
    }
 
    // print contents of arr[] 
    for (i = 0 ; i < arr.Count ; i++)
    {
        Console.WriteLine(arr[i]);
    }
}
 
// Driver program to test above function 
public static void Main(string[] args)
{
    generateGrayarr(3);
}
}
 
  // This code is contributed by Shrikant13


Javascript




<script>
// Javascript program to generate n-bit Gray codes
     
    // This function generates all n bit Gray codes and prints the
    // generated codes
    function generateGrayarr(n)
    {
        // base case
    if (n <= 0)
        return;
   
    // 'arr' will store all generated codes
    let arr = [];
   
    // start with one-bit pattern
    arr.push("0");
    arr.push("1");
   
    // Every iteration of this loop generates 2*i codes from previously
    // generated i codes.
    let i, j;
    for (i = 2; i < (1<<n); i = i<<1)
    {
        // Enter the previously generated codes again in arr[] in reverse
        // order. Nor arr[] has double number of codes.
        for (j = i-1 ; j >= 0 ; j--)
            arr.push(arr[j]);
   
        // append 0 to the first half
        for (j = 0 ; j < i ; j++)
            arr[j]= "0" + arr[j];
   
        // append 1 to the second half
        for (j = i ; j < 2*i ; j++)
            arr[j]= "1" + arr[j];
    }
   
    // print contents of arr[]
    for (i = 0 ; i < arr.length ; i++ )
        document.write(arr[i]+"<br>");
    }
     
    // Driver program to test above function
    generateGrayarr(3);
     
    // This code is contributed by unknown2108
</script>


Output

000
001
011
010
110
111
101
100

Time Complexity: O(2N)
Auxiliary Space: O(2N)

Method 2: Recursive Approach

The idea is to recursively append the bit 0 and 1 each time until the number of bits is not equal to N.

Base Condition: The base case for this problem will be when the value of N = 0 or 1.

If (N == 0)
return {“0”}
if (N == 1)
return {“0”, “1”}

Recursive Condition: Otherwise, for any value greater than 1, recursively generate the gray codes of the N – 1 bits and then for each of the gray code generated add the prefix 0 and 1.

Below is the implementation of the above approach:

C++




// C++ program to generate
// n-bit Gray codes
 
#include <bits/stdc++.h>
using namespace std;
 
// This function generates all n
// bit Gray codes and prints the
// generated codes
vector<string> generateGray(int n)
{
    // Base case
    if (n <= 0)
        return {"0"};
 
    if (n == 1)
    {
      return {"0","1"};
    }
 
    //Recursive case
    vector<string> recAns=
          generateGray(n-1);
    vector<string> mainAns;
     
    // Append 0 to the first half
    for(int i=0;i<recAns.size();i++)
    {
      string s=recAns[i];
      mainAns.push_back("0"+s);
    }
     
     // Append 1 to the second half
    for(int i=recAns.size()-1;i>=0;i--)
    {
       string s=recAns[i];
       mainAns.push_back("1"+s);
    }
    return mainAns;
}
 
// Function to generate the
// Gray code of N bits
void generateGrayarr(int n)
{
    vector<string> arr;
    arr=generateGray(n);
    // print contents of arr
    for (int i = 0 ; i < arr.size();
         i++ )
        cout << arr[i] << endl;
}
 
// Driver Code
int main()
{
    generateGrayarr(3);
    return 0;
}


Java




// Java program to generate
// n-bit Gray codes
import java.io.*;
import java.util.*;
class GFG
{
 
  // This function generates all n
  // bit Gray codes and prints the
  // generated codes
  static ArrayList<String> generateGray(int n)
  {
 
    // Base case
    if (n <= 0)
    {
      ArrayList<String> temp =
        new ArrayList<String>(){{add("0");}};
      return temp;
    }
    if(n == 1)
    {
      ArrayList<String> temp =
        new ArrayList<String>(){{add("0");add("1");}};
      return temp;
    }
 
    // Recursive case
    ArrayList<String> recAns = generateGray(n - 1);
    ArrayList<String> mainAns = new ArrayList<String>();
 
    // Append 0 to the first half
    for(int i = 0; i < recAns.size(); i++)
    {
      String s = recAns.get(i);
      mainAns.add("0" + s);
 
    }
 
    // Append 1 to the second half
    for(int i = recAns.size() - 1; i >= 0; i--)
    {
      String s = recAns.get(i);
      mainAns.add("1" + s);
    }
    return mainAns;
  }
 
  // Function to generate the
  // Gray code of N bits
  static void generateGrayarr(int n)
  {
    ArrayList<String> arr = new ArrayList<String>();
    arr = generateGray(n);
 
    // print contents of arr
    for (int i = 0 ; i < arr.size(); i++)
    {
      System.out.println(arr.get(i));   
    }
  }
 
  // Driver Code
  public static void main (String[] args)
  {
    generateGrayarr(3);
  }
}
 
// This code is contributed by rag2127.


Python3




# Python3 program to generate
# n-bit Gray codes
 
# This function generates all n
# bit Gray codes and prints the
# generated codes
def generateGray(n):
     
    # Base case
    if (n <= 0):
        return ["0"]
    if (n == 1):
        return [ "0", "1" ]
 
    # Recursive case
    recAns = generateGray(n - 1)
 
    mainAns = []
     
    # Append 0 to the first half
    for i in range(len(recAns)):
        s = recAns[i]
        mainAns.append("0" + s)
 
    # Append 1 to the second half
    for i in range(len(recAns) - 1, -1, -1):
        s = recAns[i]
        mainAns.append("1" + s)
 
    return mainAns
 
# Function to generate the
# Gray code of N bits
def generateGrayarr(n):
     
    arr = generateGray(n)
 
    # Print contents of arr
    print(*arr, sep = "\n")
 
# Driver Code
generateGrayarr(3)
 
# This code is contributed by avanitrachhadiya2155


C#




// Java program to generate
// n-bit Gray codes
using System;
using System.Collections.Generic;
class GFG {
 
  // This function generates all n
  // bit Gray codes and prints the
  // generated codes
  static List<String> generateGray(int n)
  {
 
    // Base case
    if (n <= 0) {
      List<String> temp = new List<String>();
      temp.Add("0");
      return temp;
    }
    if (n == 1) {
      List<String> temp = new List<String>();
      temp.Add("0");
      temp.Add("1");
      return temp;
    }
 
    // Recursive case
    List<String> recAns = generateGray(n - 1);
    List<String> mainAns = new List<String>();
 
    // Append 0 to the first half
    for (int i = 0; i < recAns.Count; i++) {
      String s = recAns[i];
      mainAns.Add("0" + s);
    }
 
    // Append 1 to the second half
    for (int i = recAns.Count - 1; i >= 0; i--) {
      String s = recAns[i];
      mainAns.Add("1" + s);
    }
    return mainAns;
  }
 
  // Function to generate the
  // Gray code of N bits
  static void generateGrayarr(int n)
  {
    List<String> arr = new List<String>();
    arr = generateGray(n);
 
    // print contents of arr
    for (int i = 0; i < arr.Count; i++)
    {
      Console.WriteLine(arr[i]);
    }
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    generateGrayarr(3);
  }
}
 
// This code is contributed by grand_master.


Javascript




<script>
// Javascript program to generate
// n-bit Gray codes
 
// This function generates all n
  // bit Gray codes and prints the
  // generated codes
function generateGray(n)
{
    // Base case
    if (n <= 0)
    {
      let temp =["0"];
      return temp;
    }
    if(n == 1)
    {
      let temp =["0","1"];
        
      return temp;
    }
  
    // Recursive case
    let recAns = generateGray(n - 1);
    let mainAns = [];
  
    // Append 0 to the first half
    for(let i = 0; i < recAns.length; i++)
    {
      let s = recAns[i];
      mainAns.push("0" + s);
  
    }
  
    // Append 1 to the second half
    for(let i = recAns.length - 1; i >= 0; i--)
    {
      let s = recAns[i];
      mainAns.push("1" + s);
    }
    return mainAns;
}
 
// Function to generate the
  // Gray code of N bits
function generateGrayarr(n)
{
    let arr = [];
    arr = generateGray(n);
  
    // print contents of arr
    for (let i = 0 ; i < arr.length; i++)
    {
      document.write(arr[i]+"<br>");  
    }
}
 
// Driver Code
generateGrayarr(3);
 
 
// This code is contributed by ab2127
</script>


Output

000
001
011
010
110
111
101
100

Time Complexity: O(2N)
Auxiliary Space: O(2N)

Method3: (Using bitset)

We should first find binary no from 1 to n and then convert it into string and then print it using substring function of string.

Below is the implementation of the above idea:

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
void GreyCode(int n)
{
     // power of 2
    for (int i = 0; i < (1 << n); i++)
    {
        // Generating the decimal
        // values of gray code then using
        // bitset to convert them to binary form
        int val = (i ^ (i >> 1));
         
        // Using bitset
        bitset<32> r(val);
         
        // Converting to string
        string s = r.to_string();
        cout << s.substr(32 - n) << " ";
    }
}
 
 
// Driver Code
int main()
{
    int n;
    n = 4;
   
    // Function call
    GreyCode(n);
    
    return 0;
}


Java




// Java implementation of the above approach
import java.lang.Math;
 
class GFG {
 
  static void GreyCode(int n)
  {
 
    // power of 2
    for (int i = 0; i < (1 << n); i++)
    {
 
      // Generating the decimal
      // values of gray code then using
      // bitset to convert them to binary form
      int val = (i ^ (i >> 1));
 
      // Converting to binary string
      String s = Integer.toBinaryString(val);
      System.out.print(
        String.format("%1$" + n + "s", s)
        .replace(' ', '0')
        + " ");
    }
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int n = 4;
 
    // Function call
    GreyCode(n);
  }
}
 
// This code is contributed by phasing17


Python3




# Python3 implementation of the above approach
def GreyCode(n):
 
    # power of 2
    for i in range(1 << n):
       
        # Generating the decimal
        # values of gray code then using
        # bitset to convert them to binary form
        val = (i ^ (i >> 1))
         
        # Converting to binary string
        s = bin(val)[2::]
        print(s.zfill(n), end = " ")
 
# Driver Code
n = 4
   
# Function call
GreyCode(n)
 
# This code is contributed by phasing17


Javascript




// JavaScript implementation of the above approach
function GreyCode(n)
{
 
    // power of 2
    for (var i = 0; i < (1 << n); i++)
    {
        // Generating the decimal
        // values of gray code then using
        // bitset to convert them to binary form
        var val = (i ^ (i >> 1));
         
        // Converting to binary string
        s = val.toString(2);
        process.stdout.write(s.padStart(4, '0') + " ");
    }
}
 
// Driver Code
let n = 4;
   
// Function call
GreyCode(n);
 
// This code is contributed by phasing17


C#




// C# implementation of the above approach
 
using System;
 
class GFG {
 
    static void GreyCode(int n)
    {
 
        // power of 2
        for (int i = 0; i < (1 << n); i++) {
 
            // Generating the decimal
            // values of gray code then using
            // bitset to convert them to binary form
            int val = (i ^ (i >> 1));
 
            // Converting to binary string
            string s = Convert.ToString(val, 2);
            Console.Write(s.PadLeft(4, '0') + " ");
        }
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int n = 4;
        // Function call
        GreyCode(n);
    }
}
 
// This code is contributed by phasing17


Output

0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000 

Time Complexity: O(2N)
Auxiliary Space: O(N)



Previous Article
Next Article

Similar Reads

A backtracking approach to generate n bit Gray Codes
Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) Examples: Input : 2 Output : 0 1 3 2Explanation : 00 - 001 - 111 - 310 - 2Input : 3 Output : 0 1 3 2 6 7 5 4 We have discussed an approach in Generate n-bit Gray CodesThis article provides a backtracking
6 min read
Gray to Binary and Binary to Gray conversion
Binary Number is the default way to store numbers, but in many applications, binary numbers are difficult to use and a variety of binary numbers is needed. This is where Gray codes are very useful. Gray code has a property that two successive numbers differ in only one bit because of this property gray code does the cycling through various states w
13 min read
Linde-Buzo-Gray (LBG) Algorithm
Linde-Buzo-Gray (LBG) Algorithm is used for designing of Codebook efficiently which has minimum distortion and error. LBG algorithm was proposed by Yoseph Linde, Andres Buzo and Robert M. Gray in 1980. It is the most common algorithm for Code Generation that generates a codebook with minimum error from a training set. Training sets are a set of vec
2 min read
Binary to Gray code using recursion
Given the Binary code of a number as a decimal number, we need to convert this into its equivalent Gray Code. Assume that the binary number is in the range of integers. For the larger value, we can take a binary number as string. In gray code, only one bit is changed in 2 consecutive numbers. Examples: Input: 1001 Output: 1101Explanation: 1001 -
5 min read
Decimal Equivalent of Gray Code and its Inverse
Given a decimal number n. Find the gray code of this number in decimal form. Examples: Input : 7 Output : 4 Explanation: 7 is represented as 111 in binary form. The equivalent gray code of 111 is 100 in binary form, whose decimal equivalent is 4. Input : 10 Output : 15 Explanation: 10 is represented as 1010 in binary form. The equivalent gray code
7 min read
CSES Solutions - Gray Code
A Gray code is a list of all 2n bit strings of length n, where any two successive strings differ in exactly one bit (i.e., their Hamming distance is one). Your task is to create a Gray code for a given length n. Examples: Input: n=2Output: {"00", "01", "11", "10"} Input: n=1Output: {"0", "1"} Approach: Follow the below approach to solve the problem
5 min read
Code Converters - Binary to/from Gray Code
In this article, we will go through Code Converters - Binary to/from Gray Code,we will start our article by defining Code converters, Binary code and Gray code, and then we will go through the conversion of binary code to gray code and vice versa. At last, we will conclude our article with some faqs. Table of Content Code ConvertersBinary CodeGray
9 min read
Inserting M into N such that m starts at bit j and ends at bit i | Set-2
Given two 32-bit numbers, N and M, and two-bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. Assuming index start from 0.Examples: a) N = 1024 (10000000000), M = 19 (10011), i = 2, j = 6 Output : 1100 (10001001100) b) N
10 min read
Count of 1-bit and 2-bit characters in the given binary string
Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string is always valid.Examples: Input: str = "11100" Ou
4 min read
Count bases which contains a set bit as the Most Significant Bit in the representation of N
Given a positive integer N, the task is to count the number of different bases in which, when N is represented, the most significant bit of N is a found to be a set bit. Examples: Input: N = 6Output: 4Explanation: The number 6 can be represented in 5 different bases, i.e. base 2, base 3, base 4, base 5, base 6. (6)10 in base 2: (110)2(6)10 in base
5 min read
Implementation of Bit Stuffing and Bit Destuffing
Bit Stuffing is a process of inserting an extra bit as 0, once the frame sequence encountered 5 consecutive 1's. Given an array, arr[] of size N consisting of 0's and 1's, the task is to return an array after the bit stuffing. Examples: Input: N = 6, arr[] = {1, 1, 1, 1, 1, 1}Output: 1111101Explanation: During the traversal of the array, 5 consecut
15 min read
Find the index at which bit must be set to maximise distance between next set bit
Given a binary array arr[]. The task is to find the position of any 0 in arr[] such that the distance between two set bits is maximized. Examples Input: arr = [1, 0, 0, 0, 1, 0, 1]Output: 2Explanation: Flip the bit at arr[2] Input: arr = [1, 0, 0, 0]Output: 3 Approach: The problem can be solved by finding the longest distance between adjacent set b
5 min read
Find X in range [1, N] of bit size A[i] such that X^2's bit size is not present in Array
Given an array A of N integers, where: Each element of array represents the bit size of an imaginary unsigned integer datatype.If ith imaginary datatype has a size of A[i] bits, then it can store integers from size 0 to 2A[i]-1. The task is to check if there exist some integer X, such that: X is in range 1 to NX can fit in a datatype of bit size A[
8 min read
Minimize bit flips such that each continuous segment of same bit has even length
Given a binary string S of even size that contains only 0s and 1s, the task is to find the minimum flips (that is 0 to 1 or 1 to 0) such that every contiguous subsegment that contains the same bit is of even size. Examples: Input: S = "1110011000 "Output: 3Explanation: Change S[2], S[5] and S[6] to '0'. After that S becomes "1100000000", it can be
8 min read
Find array elements with rightmost set bit at the position of the rightmost set bit in K
Given an array arr[] consisting of N and an integer K, the task is to print the elements of arr[] whose rightmost set bit is at the same position as the rightmost set bit in K. Examples: Input: arr[] = { 3, 4, 6, 7, 9, 12, 15 }, K = 7Output: { 3, 7, 9, 15 }Explanation:Binary representation of K (= 7) is 0111.Rightmost set bit in 7 is at position 1.
11 min read
Inserting m into n such that m starts at bit j and ends at bit i.
We are given two numbers n and m, and two-bit positions, i and j. Insert bits of m into n starting from j to i. We can assume that the bits j through i have enough space to fit all of m. That is, if m = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because m could not fully f
8 min read
Distinct state codes that appear in a string as contiguous sub-strings
Every state is represented by string of length 2. For example DL is used for Delhi, HP for Himachal Pradesh, UP for Uttar Pradesh, PB for Punjab etc. Given a string str consisting of uppercase English alphabets only, the task is to find the number of distinct state codes that appear in the string as contiguous sub-strings.Examples: Input: str = "UP
4 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
Remove one bit from a binary number to get maximum value
Given a binary number, the task is to remove exactly one bit from it such that, after it's removal, the resultant binary number is greatest from all the options.Examples: Input: 110 Output: 11 As 110 = 6 in decimal, the option is to remove either 0 or 1. So the possible combinations are 10, 11 The max number is 11 = 3 in decimal. Input:1001 Output:
4 min read
Index of kth set bit in a binary array with update queries
Given a binary array arr[] and q queries of following types: k: find the index of the kth set bit i.e. kth 1 in the array.(x, y): Update arr[x] = y where y can either be a 0 or 1. Examples: Input: arr[] = {1, 0, 1, 0, 0, 1, 1, 1}, q = 2 k = 4 (x, y) = (5, 1) Output: Index of 4th set bit: 6 Array after updation: 1 0 1 0 0 0 1 1 Approach: A simple so
15+ min read
Find majority element using Bit Magic
Pre-requisite: Majority Element, Majority Element | Set-2 (Hashing)Given an array of size N, find the majority element. The majority element is the element that appears more than n/2 times in the given array. Examples: Input: {3, 3, 4, 2, 4, 4, 2, 4, 4} Output: 4 Input: {3, 3, 6, 2, 4, 4, 2, 4} Output: No Majority Element Approach:In this post, we
8 min read
Check if a number is positive, negative or zero using bit operators
Given a number N, check if it is positive, negative or zero without using conditional statements.Examples: Input : 30 Output : 30 is positive Input : -20 Output : -20 is negative Input: 0 Output: 0 is zero The signed shift n>>31 converts every negative number into -1 and every other into 0. When we do a -n>>31, if it is a positive numbe
5 min read
Set the Left most unset bit
Given an integer, set the leftmost unset bit. Leftmost unset bit is the first unset bit after most significant set bit. If all bits (after most significant set bit) are set, then return the number. Examples: Input : 10 Output : 14 10 = 1 0 1 0 // 10 binary 14 = 1 1 1 0 // after set left most unset bit Input : 15 Output : 15 15 = 1 1 1 1 // 15 binar
5 min read
Position of rightmost bit with first carry in sum of two binary
Given two non-negative integers a and b. The problem is to find the position of the rightmost bit where a carry is generated in the binary addition of a and b. Examples: Input : a = 10, b = 2 Output : 2 (10)10 = (1010)2 (2)10 = (10)2. 1010 + 10 As highlighted, 1st carry bit from the right will be generated at position '2'. Input : a = 10, b = 5 Out
4 min read
Check whether the bit at given position is set or unset
Given two positive integers n and k. The problem is to check whether the bit at position k from the right in the binary representation of n is set ('1') or unset ('0'). Constraints: 1 <= k <= number of bits in the binary representation of n.Examples: Input : n = 10, k = 2 Output : Set (10)10 = (1010)2 The 2nd bit from the right is set. Input
10 min read
Make Binary Strings equal by replacing 2nd bit repeatedly
Given two binary strings S and T of size N and M respectively, the task is to check if S can be converted into T by doing the following operations, any number of times: Suppose a is the first character of S and b is the second character of S. Change the second character of S to either min(a, b) or max(a, b), and remove the first character. Note tha
7 min read
For every set bit of a number toggle bits of other
Given two integer numbers, whenever the bits of the first number is set i.e. 1, toggle the bits of the second number leaving the rest bits of the second number unchanged. Examples : Input: 2 5 Output: 7 2 is represented as 10 in binary and 5 is represented as 101. Hence toggling the 2nd bit of 5 from right, thus the new number becomes 7 i.e. 111 In
3 min read
Space optimization using bit manipulations
There are many situations where we use integer values as index in array to see presence or absence, we can use bit manipulations to optimize space in such problems.Let us consider below problem as an example.Given two numbers say a and b, mark the multiples of 2 and 5 between a and b using less than O(|b - a|) space and output each of the multiples
12 min read
Find value of k-th bit in binary representation
Given a number n and k (1 <= k <= 32), find the value of k-th bit in the binary representation of n. Bits are numbered from right (Least Significant Bit) to left (Most Significant Bit). Examples : Input : n = 13, k = 2 Output : 0 Explanation: Binary representation of 13 is 1101. Second bit from right is 0. Input : n = 14, k = 3 Output : 1 Exp
5 min read
Minimum bit changes in Binary Circular array to reach a index
Given a Binary Circular Array of size N elements and two positive integers x and y indicating the indices in the circular array. The task is check which path, clockwise or anti-clockwise, from index x to index y, we face the minimum number bit flips. Output "Clockwise" or "Anti-clockwise" and the value of minimum bit flip, in case of equal count ou
9 min read