The Wayback Machine - https://web.archive.org/web/20240915115527/https://www.geeksforgeeks.org/decimal-equivalent-gray-code-inverse/
Open In App

Decimal Equivalent of Gray Code and its Inverse

Last Updated : 07 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Medium
68.7%
52.3K

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 
of 1010 is 1111 in binary form, whose decimal equivalent is 15. 

Recommended Practice

The following table shows the conversion of binary code values to gray code values: 

Decimal Value Binary Equivalent Gray Code Equivalent Decimal Value of Gray Code Equivalent
0 000 000 0
1 001 001 1
2 010 011 3
3 011 010 2
4 100 110 6
5 101 111 7
6 110 101 5
7 111 100 4

Below is the approach for the conversion of decimal code values to gray code values. 
Let G(n) be the Gray code equivalent of binary representation n. Consider bits of a number n and a number bit G(n). Note that the leftmost set bits of both n and G(n) are in the same position. Let this position be i and positions on the right of it be (i+1), (i+2), etc. The (i + 1)th bit in G(n) is 0 if (i+1)th bit in n is 1 and vice versa is also true. The same is true for (i+2)-th bits, etc. Thus we have G (n) = n xor (n >> 1): 

C++





Java





Python3





C#





PHP





Javascript





Output: 

15

 

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

Finding the Inverse Gray Code 
Given a decimal equivalent number n of a gray code. Find its original number in decimal form.

Examples: 

Input : 4 
Output : 7

Input : 15 
Output : 10

Below is the approach for the conversion of gray code values to decimal code values. 
We will go from the older bits to the younger ones (even the smallest bit has the number 1, and the oldest bit is numbered k). We obtain such relations between the bits of the ni number n and the bits of the gi number g: 

 Steps to solve this problem:

  • Initialize a variable inv to 0.
  •  Iterate over the binary digits of n from the rightmost digit to the leftmost digit and right shift n by one bit.
    • Take the bitwise XOR of the current value of inv with the value of n.
  • return the value of inv.
 nk = gk, 
 nk-1 = gk-1 xor nk = gk xor gk-1
 nk-2 = gk-2 xor nk-1 = gk xor gk-1 xor gk-2 
 nk-3 = gk-3 xor nk-2 = gk xor gk-1 xor gk-2 xor gk-3
 ... 

C++





Java





Python3





C#




// C# Program to convert given
// decimal number of gray code
// into its inverse in decimal form
using System;
 
class GFG {
     
    // Function to convert given
    // decimal number of gray code
    // into its inverse in decimal form
    static int inversegrayCode(int n)
    {
        int inv = 0;
     
        // Taking xor until n becomes zero
        for ( ; n != 0 ; n = n >> 1)
            inv ^= n;
     
        return inv;
    }
     
    // Driver code
    public static void Main ()
    {
        int n = 15;
        Console.Write(inversegrayCode(n));
    }
}
 
// This code is contributed by nitin mittal.


PHP





Javascript





Output: 

10

 

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

Please suggest if someone has a better solution which is more efficient in terms of space and time.



Similar Reads

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
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
Program to convert Hexa-Decimal Number to its equivalent BCD
Given a HexaDecimal Number N, the task is to convert the number to its equivalent Binary Coded Decimal.Examples: Input: 11F Output: 0001 0001 1111 Explanation: Binary of 1 - 0001 Binary of F - 1111 Thus, Equivalent BCD is 0001 0001 1111Input: A D Output: 1010 1101 Explanation: Binary of A - 1010 Binary of D - 1101 Thus, Equivalent BCD is 1010 1101
10 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
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
Sum of decimal equivalent of all possible pairs of Binary representation of a Number
Given a number N. The task is to find the sum of the decimal equivalent of all the pairs formed from the binary representation of the given number. Examples: Input: N = 4 Output: 4 Binary equivalent of 4 is 100. All possible pairs are 10, 10, 00 and their decimal equivalent are 2, 2, 0 respectively. So, 2 + 2+ 0 = 4 Input: N = 11 Output: 13 All pos
5 min read
Count of substrings whose Decimal equivalent is greater than or equal to K
Given an integer K and a binary string S of length N, the task is to find out the number of substrings whose decimal equivalent is greater than or equal to K. Examples: Input: K = 3, S = "11100" Output: 8 Explanation: There are 8 such substring whose decimal equivalent is greater than or equal to 3, as mentioned below: Substring - Decimal Equivalen
12 min read
Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
Given a binary-valued Undirected Graph with V vertices and E edges, the task is to find the maximum decimal equivalent among all the connected components of the graph. A binary-valued graph can be considered as having only binary numbers (0 or 1) as the vertex values. Examples: Input: E = 4, V = 7 Output: 3 Explanation: Decimal equivalents of the c
14 min read
Check if level-wise Decimal equivalent of Binary Tree forms a Monotonic sequence or not
Given the root of a binary tree in which all nodes has values either 0 or 1, the task is to check if the level-wise decimal equivalent of given Tree forms a monotonic sequence.or not. A sequence is monotonic if it is either monotone increasing or monotone decreasing. A sequence nums is monotone increasing if for all i <= j, nums[i] <= nums[j]
15+ min read
Decimal Equivalent of Binary Linked List
Given a singly linked list of 0s and 1s find its decimal equivalent. Input : 0->0->0->1->1->0->0->1->0 Output : 50 Input : 1->0->0 Output : 4The decimal value of an empty linked list is considered as 0. Recommended PracticeDecimal Equivalent of Binary Linked ListTry It!Initialize the result as 0. Traverse the linked li
10 min read
Javascript Program To Find Decimal Equivalent Of Binary Linked List
Given a singly linked list of 0s and 1s find its decimal equivalent. Input: 0->0->0->1->1->0->0->1->0Output: 50 Input: 1->0->0Output: 4The decimal value of an empty linked list is considered as 0. Initialize the result as 0. Traverse the linked list and for each node, multiply the result by 2 and add the node's data to
3 min read
Convert the given BCD to its equivalent Binary form
Given a BCD (Binary Coded Decimal), the task is to convert this to its equivalent Binary number. Examples: Input: 1001000 Output: 110000 Explanation: Integer value of the given BCD is 48(0100 -> 4, 1000 -> 8). (48)10 = (110000)2 Input: 1001001 Output: 110000 Approach: In order to solve this problem we need to split the given BCD number into b
6 min read
Convert a sentence into its equivalent mobile numeric keypad sequence
Given a sentence in the form of a string, convert it into its equivalent mobile numeric keypad sequence.  Examples :  Input: GEEKSFORGEEKSOutput: 4333355777733366677743333557777Explanation: For obtaining a number, we need to press a number corresponding to that character for a number of times equal to the position of the character. For example, for
6 min read
Program to convert given Binary to its equivalent ASCII character string
Given a binary string str, the task is to find its equivalent ASCII (American Standard Code for Information Interchange) character string. Examples: Input: str = "0110000101100010"Output: abExplanation: Dividing str into set of 8 bits as follows: 01100001 = 97, ASCII value of 97 is 'a'.01100010 = 98, ASCII value of 98 is 'b'.Therefore, the required
9 min read
Convert the ASCII value sentence to its equivalent string
Given a string str which represents the ASCII (American Standard Code for Information Interchange) Sentence, the task is to convert this string into its equivalent character sequence. Examples: Input: str = "71101101107115" Output: Geeks 71, 101, 101, 107 are 115 are the unicode values of the characters 'G', 'e', 'e', 'k' and 's' respectively.Input
5 min read
Print given sentence into its equivalent ASCII form
Given a string containing words forming a sentence (belonging to the English language). The task is to output the equivalent ASCII sentence of the input sentence. ASCII (American Standard Code for Information Interchange) form of a sentence is the conversion of each of the characters of the input string and aligning them in the position of characte
4 min read
Check if the given array is same as its inverse permutation
Given an array arr[] consisting of integers in the range [1, N], the task is to determine whether the Inverse Permutation of the given array is same as the given array. An inverse permutation is a permutation obtained by inserting the position of all elements at the position equal to the respective values of the element in the array.Illustration: a
8 min read
Generate n-bit Gray Codes
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
14 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
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
Given a number N in decimal base, find number of its digits in any base (base b)
Given A Number n in a base 10, find the number of digits in its base b representation. Constraints : [Tex]N \in \mathbb{W} [/Tex]Whole Examples : Input : Number = 48 Base = 4 Output: 3 Explanation : (48)10 = (300)4 Input : Number = 1446 Base = 7 Output: 4 Explanation : (446)10 = (4134)7 A simple approach: convert the decimal number into the given b
8 min read
Convert a given Decimal number to its BCD representation
Given a decimal number N, the task is to convert N to it's Binary Coded Decimal(BCD) form.Examples: Input: N = 12 Output: 0001 0010 Explanation: Considering 4-bit concept: 1 in binary is 0001 and 2 in binary is 0010. So it's equivalent BCD is 0001 0010. Input: N = 10 Output: 0001 0000 Explanation: Considering 4-bit concept: 1 in binary is 0001 and
5 min read
Check whether two strings are equivalent or not according to given condition
Given two strings A and B of equal size. Two strings are equivalent either of the following conditions hold true: 1) They both are equal. Or, 2) If we divide the string A into two contiguous substrings of same size A1 and A2 and string B into two contiguous substrings of same size B1 and B2, then one of the following should be correct: A1 is recurs
12 min read
Check whether the binary equivalent of a number ends with "001" or not
Given a positive integer N, the task is to check whether the binary equivalent of that integer ends with "001" or not. Print "Yes" if it ends in "001". Otherwise, Print "No". Examples : Input: N = 9 Output: Yes Explanation Binary of 9 = 1001, which ends with 001 Input: N = 5 Output: No Binary of 5 = 101, which does not end in 001 Naive Approach Fin
12 min read
Check whether the binary equivalent of a number ends with given string or not
Given a positive integer N, the task is to check whether the binary equivalent of that integer ends with the given string str or not. Print "Yes" if it ends in "str". Otherwise, Print "No".Examples: Input: N = 23, str = "111"Output: YesExplanation:Binary of 23 = 10111, which ends with "111" Input: N = 5, str = "111"Output: No Approach: The idea is
5 min read
Convert given Float value to equivalent Fraction
Given a floating-point number in the form of a string N, the task is to convert the given floating-point number into fractions. Enclosed sequence of digits in "()" in the floating-point representation expresses recurrence in the decimal representation. For example, 1.(6) represents 1.666.... Examples: Input: N = "1.5"Output: 3 / 2Explanation:The va
11 min read
Check if a Float value is equivalent to an Integer value
Given a floating-point number N, the task is to check if the value of N is equivalent to an integer or not. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: N = 1.5Output: NO Input: N = 1.0Output: YES Approach: The idea is to use the concept of Type Casting. Follow the steps below to solve the problem: Initialize a var
3 min read
Minimum insertions or deletions required to make two strings K-equivalent
Given two strings str1 and str2, the task is to find the minimum number of operations required to map each character of the string str1 to K ( < 1000) similar characters of the string str2 by either inserting a character into str2 or by removing a character from str2. Examples: Input: str1 = "aab", str2 = "aaaabb"Output: 0Explanation: Map {str2[
10 min read
Program to convert polar co-ordinates to equivalent cartesian co-ordinates
Given two integers r and ? (in degree) representing polar coordinates of a point (r, ?), the task is to find the Cartesian coordinates of the given point. Examples: Input: r = 1.4142, ? = 45Output: 1.000, 1.000 Input: r = 3, ? = 30Output: 2.598, 1.500 Approach: Let the cartesian coordinates of the point be (x, y). The polar coordinates and the Cart
4 min read
Equivalent Serial Schedule of Conflict Serializable Schedule in DBMS
Prerequisite: Conflict Serializability, Precedence Graph Conflict Serializable Schedule: A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. The serial schedule of the Conflict Serializable Schedule can be found by applying topological Sorting on the Precedence Graph of
12 min read