Given N in Gray code equivalent. Find its binary equivalent and return decimal form using bitset in O(1)
Examples :
Input 4: Output 7: Input 15: Output 10:
We are using bitset class of C++ for handling bits of the number.We are traversing number from left and taking xor of previous bit of the result with current bit.
Note : MSB of number is copied directly into result
Implementation :
#include<bits/stdc++.h>
using namespace std;
int grayToBinary(int n)
{
bitset<32>b;
bitset<32>c;
//converting number into bitset
b|=n;
//iterating through all bit of the numbers
for(int i=31;i>=0;i--)
{
c[i]=b[i]^(i==31?0:c[i+1]);
}
return (int)c.to_ulong();
}
int main()
{
cout<<grayToBinary(4)<<"\n"; cout<<grayToBinary(15)<<"\n"; return 0;
}