十进制(N) | 自然二进制B(N) | 典型格雷码G(N) |
0 | 000 | 000 |
1 | 001 | 001 |
2 | 010 | 011 |
3 | 011 | 010 |
4 | 100 | 110 |
5 | 101 | 111 |
6 | 110 | 101 |
7 | 111 | 100 |
典型格雷码的数学规律:G(N) = B(N)>>1 XOR B(N)
public class Main { public static void main(String[] args) { System.out.println(grayGode(3)); } public static List<Integer> grayGode(int n){ int nums = (int)Math.pow(2,n); List<Integer> list = new ArrayList<>(); for (int i = 0; i < nums; i++) { list.add(2^i>>1 ^ 2^i); } return list; } }
参考:https://leetcode-cn.com/problems/gray-code/solution/ge-lei-ma-shu-xue-xing-zhi-by-world-16