Gray code
InterviewTime limit1sMemory limit128 MB
Convert an n-bit binary string to its standard Gray code by copying the first bit and adding each adjacent pair of bits without carry.
- Level
Easy1 of 10
- Topics
- Bit manipulation, String
- Solved
- No attempts yet
Problem
A binary number is a number in base , where each digit, or bit, has a weight that is a power of . For example, the decimal number is written in binary because
A Gray code sequence is a sequence of binary values in which each value differs from its immediate predecessor in exactly one bit. The table below shows the standard Gray code sequence for 3-bit binary numbers.
Converting a binary number into its standard Gray code value takes a very simple algorithm. Say we convert the binary value . Start by copying the first bit.
0 1 1
v
0
The second bit comes from adding the first and second bits of the given binary number, giving the sum .
0 + 1 1
v
0 1
The third bit comes from adding the second and third bits of the given binary number, giving the sum in binary. We discard the carry, so we take only the rightmost bit of the sum.
0 1 + 1
v
0 1 0
The answer is therefore .
In general, apart from the first bit, the -th bit of the standard Gray code comes from adding the -th bit and the -th bit of the given binary number and discarding the carry. These four cases describe the carry-discarding addition completely.
0 0 1 1
+ 0 + 1 + 0 + 1
--- --- --- ---
0 1 1 0
Write a program that converts an -bit binary value into its equivalent -bit standard Gray code value, where .
Input
The input consists of two lines.
- The first line contains the integer , the number of bits, where .
- The second line contains a bit string of length representing the -bit binary number.
Output
Print a bit string of length , the standard Gray code equivalent of the given -bit binary number.