Gray Code(Medium)格雷码

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

Java实现

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2


Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according 
to the above definition.

For now, the judge is able to judge based on one instance of gray 
code sequence. Sorry about that.

public List<Integer> grayCode(int n) {}
public ArrayList<Integer> grayCode(int n) {
    ArrayList<Integer> arr = new ArrayList<Integer>();
    arr.add(0);
    for(int i=0;i<n;i++){
        int inc = 1<<i;
        for(int j=arr.size()-1;j>=0;j--){
            arr.add(arr.get(j)+inc);
        }
    }
    return arr;
}

OR

List<Integer> grayCode2(int n) {
    List<Integer> arr = new ArrayList<Integer>();
    int i,j;
    int bit=1;
    arr.add(0);

    for(i=0;i<n;i++){
        for(j=arr.size()-1;j>=0;j--){
            arr.add(arr.get(j) | bit);
        }
        bit <<= 1;
    }
    return arr;
}

Python实现


class Solution:
    # @return a list of integers
    @staticmethod
    def graycode(n):
        result = [0]
        for i in range(n):
            bit=1<<i
            for n in reversed(result):
                result.append(bit | n)
        return result

if __name__ == "__main__":
    print(Solution().graycode(4))

References

1 What is the best solution for Gray Code problem?

results matching ""

    No results matching ""