One line Python solution with comments

  • 10

    These characteristics suggest a simple and fast method of translating a binary value into the corresponding Gray code. Each bit is inverted if the next higher bit of the input value is set to one. This can be performed in parallel by a bit-shift and exclusive-or operation if they are available: g(b) = x(b) XOR x(b+1)

    class Solution:
    # @param {integer} n
    # @return {integer[]}
    def grayCode(self, n):
        return [(i>>1)^i for i in xrange(2**n)]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.