This page is still under construction.

Parts of this page are still being built. What you see may change.

Gray code

Interview

Time limit1sMemory limit128 MB

Summary
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 22, where each digit, or bit, has a weight that is a power of 22. For example, the decimal number 2323 is written 1011110111 in binary because

(1×24)+(0×23)+(1×22)+(1×21)+(1×20)=16+4+2+1=23(1 \times 2^4) + (0 \times 2^3) + (1 \times 2^2) + (1 \times 2^1) + (1 \times 2^0) = 16 + 4 + 2 + 1 = 23

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.

Binary sequence000001010011100101110111
Standard Gray code sequence000001011010110111101100

Converting a binary number into its standard Gray code value takes a very simple algorithm. Say we convert the binary value 011011. 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=10 + 1 = 1.

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 1+1=101 + 1 = 10 in binary. We discard the carry, so we take only the rightmost bit 00 of the sum.

0 1 + 1
      v
0 1   0

The answer is therefore 010010.

In general, apart from the first bit, the kk-th bit of the standard Gray code comes from adding the (k−1)(k-1)-th bit and the kk-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 nn-bit binary value into its equivalent nn-bit standard Gray code value, where 1≤n≤201 \le n \le 20.

Input

The input consists of two lines.

  1. The first line contains the integer nn, the number of bits, where 1≤n≤201 \le n \le 20.
  2. The second line contains a bit string of length nn representing the nn-bit binary number.

Output

Print a bit string of length nn, the standard Gray code equivalent of the given nn-bit binary number.

Examples6

  1. Example 1

    Input
    3
    011
    
    Expected output
    010
    
  2. Example 2

    Input
    5
    01110
    
    Expected output
    01001
    
  3. Example 3

    Input
    6
    111111
    
    Expected output
    100000
    
  4. Example 4

    Input
    7
    1001001
    
    Expected output
    1101101
    
  5. Example 5

    Input
    9
    000111000
    
    Expected output
    000100100
    
  6. Example 6

    Input
    5
    10101
    
    Expected output
    11111