4
头图

Gray coding

Topic description: Gray coding is a binary number system in which two consecutive numbers differ by only one digit.

Given a non-negative integer n representing the total number of bits encoded, print its Gray-coded sequence. Even if there are multiple different answers, you only need to return one of them.

Gray-coded sequences must start with 0.

For example descriptions, please refer to the official website of LeetCode.

Source: LeetCode
Link: https://leetcode-cn.com/problems/gray-code/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

Solution 1: Binary Operations
finds the law : the total number of Gray codes of n, that is, all Gray codes of n-1 plus all Gray codes of n-1 plus 1 in front. So it can be solved according to this rule.
import java.util.ArrayList;
import java.util.List;

public class LeetCode_089 {

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

    public static void main(String[] args) {
        for (Integer s : grayCode(2)) {
            System.out.println(s);
        }
    }
}
[Daily Message] One's deep expectation can not only create one's own opportunities, but also create one's own genius!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!