leetcode 刷题之路 89 Gray Code
2014-08-13 17:11
465 查看
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
gray code sequence is:
给定位数n,按顺序输出n位格雷码对应的整数。
思路,格雷码和自然二进制有如下对应关系:
二进制码->格雷码(编码):从最右边一位起,依次将每一位与左边一位异或(XOR),作为对应格雷码该位的值,最左边一位不变(相当于左边是0),用计算式表示就是:
G=B^(B>>1)
根据上面的关系式,不难写出程序。
Accepted Solution:
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
给定位数n,按顺序输出n位格雷码对应的整数。
思路,格雷码和自然二进制有如下对应关系:
二进制码->格雷码(编码):从最右边一位起,依次将每一位与左边一位异或(XOR),作为对应格雷码该位的值,最左边一位不变(相当于左边是0),用计算式表示就是:
G=B^(B>>1)
根据上面的关系式,不难写出程序。
Accepted Solution:
class Solution { public: vector<int> grayCode(int n) { vector<int> res; res.resize(1<<n); int len=res.size(); for(int i=0;i<len;i++) res[i]=((i>>1)^i); return res; } };
相关文章推荐
- LeetCode89 Gray Code
- [leetcode 89] Gray Code---实现格雷码
- [leetcode 89] Gray Code
- 【Leetcode】:89. Gray Code 问题 in JAVA
- [LeetCode]89. Gray Code
- Leetcode: 89. Gray Code
- leetcode_89题——Gray Code(回溯法)
- leetcode - 89.Gray Code
- Leetcode 89. Gray Code 格雷码 解题报告
- [leetcode-89]Gray Code(c++)
- leetcode89~Gray Code
- LeetCode | 89. Gray Code
- LeetCode89 Gray Code
- leetCode 89.Gray Code (格雷码) 解题思路和方法
- [leetcode] #89 Gray Code
- [Leetcode] 89. Gray Code 解题报告
- leetcode 89. Gray Code
- LeetCode 89 Gray Code (Python详解及实现)
- Leetcode-89. Gray Code
- [LeetCode] 89. Gray Code 格雷码