LeetCode Online Judge 题目C# 练习 - Gray Code
2012-09-07 04:58
281 查看
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 - 0
01 - 1
11 - 3
10 - 2
Gray Code, 每次看每次都不记得。写下来让自己好温习。
Gray Code 0 = 0, 下一项是toggle最右边的bit(LSB), 再下一项是toggle最右边值为 “1” bit的左边一个bit。然后重复
如: 3bit
Gray Code: 000, 001, 011, 010, 110, 111, 101, 100, 最右边值为 “1” 的bit在最左边了,结束。
Binary : 000, 001, 010, 011, 100, 101, 110, 111
再者就是Binary Code 转换为Gray Code了。
如:
Binary Code :1011 要转换成Gray Code
1011 = 1(照写第一位), 1(第一位与第二位异或 1^0 = 1), 1(第二位异或第三位, 0^1=1), 0 (1^1 =0) = 1110
其实就等于 (1011 >> 1) ^ 1011 = 1110
有了上面的等式写code就简单了
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
Gray Code, 每次看每次都不记得。写下来让自己好温习。
Gray Code 0 = 0, 下一项是toggle最右边的bit(LSB), 再下一项是toggle最右边值为 “1” bit的左边一个bit。然后重复
如: 3bit
Gray Code: 000, 001, 011, 010, 110, 111, 101, 100, 最右边值为 “1” 的bit在最左边了,结束。
Binary : 000, 001, 010, 011, 100, 101, 110, 111
再者就是Binary Code 转换为Gray Code了。
如:
Binary Code :1011 要转换成Gray Code
1011 = 1(照写第一位), 1(第一位与第二位异或 1^0 = 1), 1(第二位异或第三位, 0^1=1), 0 (1^1 =0) = 1110
其实就等于 (1011 >> 1) ^ 1011 = 1110
有了上面的等式写code就简单了
public static List<int> GrayCode(int n) { List<int> ret = new List<int>(); int size = 1; while (n-- > 0) size *= 2; //calculate how many number would be. 2^n for (int i = 0; i < size; i++) { ret.Add((i >> 1) ^ i); } return ret; }
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - 3SUM Closest
- LeetCode Online Judge 题目C# 练习 - Combination Sum
- LeetCode Online Judge 题目C# 练习 - Merge Sorted Array
- LeetCode Online Judge 题目C# 练习 - Same Tree
- LeetCode Online Judge 题目C# 练习 - String to Integer (atoi)
- LeetCode Online Judge 题目C# 练习 - Valid Number
- LeetCode Online Judge 题目C# 练习 - Sprial Matrix
- LeetCode Online Judge 题目C# 练习 - Regular Expression Matching
- LeetCode Online Judge 题目C# 练习 - Subsets
- LeetCode Online Judge 题目C# 练习 - Valid Sudoku
- LeetCode Online Judge 题目C# 练习 - Subsets II
- LeetCode Online Judge 题目C# 练习 - Edit Distance
- LeetCode Online Judge 题目C# 练习 - Word Search
- LeetCode Online Judge 题目C# 练习 - Add two number
- LeetCode Online Judge 题目C# 练习 - Binary Tree Inorder Traversal
- LeetCode Online Judge 题目C# 练习 - Implement strStr()
- LeetCode Online Judge 题目C# 练习 - 4SUM
- LeetCode Online Judge 题目C# 练习 - ZigZag Conversion
- LeetCode Online Judge 题目C# 练习 - Combination
- LeetCode Online Judge 题目C# 练习 - Longest Substring Without Repeating Characters