[LeetCode]Gray Code
来源:互联网 发布:mac开机显示问号文件夹 编辑:程序博客网 时间:2024/06/06 01:22
题目描述
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.
For example, given n = 2, return [0,1,3,2]
. Its gray code sequence is:
00 - 001 - 111 - 310 - 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.
给出一种格雷码的实现。解题思路
什么是Gray Code?
在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码(Gray Code),另外由于最大数与最小数之间也仅一位数不同,即“首尾相连”,因此又称循环码或反射码。在数字系统中,常要求代码按一定顺序变化。例如,按自然数递增计数,若采用8421码,则数0111变到1000时四位均要变化,而在实际电路中,4位的变化不可能绝对同时发生,则计数中可能出现短暂的其它代码(1100、1111等)。
怎样解题?
乍一看题目貌似很麻烦。每一次将二进制码中的一位和上一个数相同的一位改变。怎样实现呢?
思路1:
通过观察我们发现一种实现格雷码的方法:
grayCode(n) = grayCode(n-1) + (grayCode(n)+2^(n-1))逆转;
思路2:
这个是参考网上的帖子才知道的。
二进制码->格雷码(编码):从最右边一位起,依次将每一位与左边一位异或(XOR),作为对应格雷码该位的值,最左边一位不变(相当于左边是0);
格雷码->二进制码(解码):从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变)。
格雷码->二进制码(解码):从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变)。
这种方法更具有普适性,而且代码精炼。
代码
思路1代码:
public static ArrayList<Integer> grayCode(int n) {ArrayList<Integer> list = new ArrayList<Integer>(n);if(n==0){list.add(0);return list;}if(n==1){list.add(0);list.add(1);return list;}ArrayList<Integer> childList = grayCode(n-1);int pow = (int) Math.pow(2, n-1);list.addAll(childList);for(int i = childList.size() - 1;i >= 0;i--){list.add(childList.get(i) + pow);}return list;}
思路2代码:
public static ArrayList<Integer> grayCode(int n) {ArrayList<Integer> list = new ArrayList<Integer>(n);if(n==0){list.add(0);return list;}int nSize = 1 << n; for (int i = 0; i < nSize; ++i) { list.add((i>>1)^i); } return list;}
0 0
- LeetCode: Gray Code
- [LeetCode] 格雷码(Gray Code)
- LeetCode Gray Code
- [Leetcode] Gray Code
- [LeetCode] Gray Code
- leetcode 112: Gray Code
- LeetCode Gray Code
- [leetCode] Gray Code
- [LeetCode]Gray Code
- Leetcode: Gray Code
- [leetcode]Gray Code
- LeetCode-Gray Code
- [leetcode] Gray Code
- LeetCode - Gray Code
- leetcode之Gray code
- LeetCode:Gray Code
- 【转载】【leetcode】Gray Code
- LeetCode - Gray Code
- 数据库内连接与外连接
- 二叉搜索树(二叉排序树,二叉查找树)BST
- 花若盛開,蝴蝶自來。人若精彩,天自安排。
- MyEclipse非常方便的快捷键
- Makefile命令中的@和-符号
- [LeetCode]Gray Code
- jquery实现页面无刷新动态上传图片预览功能
- IO流七:字符编码、转换流的字符编码、编码与解码、IO流练习
- SWD和JTAG的对应关系
- vi编辑器
- linux,/etc/passwd,/etc/shadow详解
- 单例饿汉式与懒汉式的区别
- 如果你是dj
- IOS 应用评论机制