LeetCode——Gray Code
2014-04-28 17:18
246 查看
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
Note:
For a given n, a gray code sequence is not uniquely defined.
For example,
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
题目大意:
给定一个n,是二进制的位数,任务是从0开始,下一个二进制数与上一个只有其中一位不同,不可重复,将这些二进制数对应的十进制数放入数组,返回这个数据。
PS,顺序不唯一,LeetCode的OJ判断符合要求即可。
举个例子:
00 --> 01 --> 11 --> 10
000 --> 001 --> 011 --> 010 --> 110 --> 111 --> 101 --> 100
不知道众位看官发现规律了没,看n=2的例子,前两个首位不变,变后面那一位,后两个不看首位的1,后面的那位与前两个是对称的。
看n=3的例子的前4个,是n=2的例子在前面加个0而已,后四个与前四个对称,把前面的0换成1。
知道对称有什么用呢?
有大用!
例如n=3的情形,你可以由前两个推后两个,这就有4个了,哈哈哈,由这四个推后四个,搞定!看代码~
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 - 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.
题目大意:
给定一个n,是二进制的位数,任务是从0开始,下一个二进制数与上一个只有其中一位不同,不可重复,将这些二进制数对应的十进制数放入数组,返回这个数据。
PS,顺序不唯一,LeetCode的OJ判断符合要求即可。
举个例子:
00 --> 01 --> 11 --> 10
000 --> 001 --> 011 --> 010 --> 110 --> 111 --> 101 --> 100
不知道众位看官发现规律了没,看n=2的例子,前两个首位不变,变后面那一位,后两个不看首位的1,后面的那位与前两个是对称的。
看n=3的例子的前4个,是n=2的例子在前面加个0而已,后四个与前四个对称,把前面的0换成1。
知道对称有什么用呢?
有大用!
例如n=3的情形,你可以由前两个推后两个,这就有4个了,哈哈哈,由这四个推后四个,搞定!看代码~
public ArrayList<Integer> grayCode(int n) { ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(0); for (int i = 0; i < n; i++) { int xchg = 1 << i; int j = arrayList.size() - 1; do { int next = arrayList.get(j) + xchg; arrayList.add(next); } while (j-- > 0); } return arrayList; }
相关文章推荐
- LeetCode (Gray Code)
- leetcode89-Gray Code(格雷码)
- [leetcode]Gray Code
- [leetcode]Gray Code
- [LeetCode]Gray Code
- Leetcode 之 Gray Code
- LeetCode89——Gray Code
- *LeetCode 89. Gray Code 规律题
- Leetcode 89. Gray Code
- LeetCode之Gray Code
- LeetCode:Gray Code
- LeetCode_89_Gray Code 格雷码
- [leetcode 89] Gray Code
- Gray Code (格雷码编码) 【leetcode】
- LeetCode 89 Gray Code
- LeetCode——Gray Code
- 【Leetcode】Gray Code (Pascal)
- leetcode 89. Gray Code
- LeetCode 89 Gray Code
- LeetCode-Gray Code