码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Gray Code

时间:2014-10-27 20:59:08      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   for   sp   div   on   

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

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(t) = binary_code(t) //t是最高位

     gray_code(i) = binary_code(i) ^binary_code(i + 1)  // 0<= i < t;

 1 class Solution {
 2 public:
 3     vector<int> grayCode(int n) {
 4         vector<int> res;
 5         const int size = 1 << n;
 6         for (int i = 0; i < size; ++i) {
 7             res.push_back((i>>1) ^ i);
 8         }
 9         
10         return res;
11         
12     }
13 };

 

拓展:

  1. 格雷码转二进制:二进制最高位是为格雷码的最高位。二进制次高位是二进制高位与格雷码次高位异或,其他各位与次高位求法相同

      binary_code(t) = gray_code(t) //t是最高位

      binary_code(i) = gray_code(i) ^ binary_code(i +1) // 0 <=i < t

 

  2. 整数n的格雷码为: n^(n/2)

 

[LeetCode] Gray Code

标签:style   blog   io   color   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/vincently/p/4054977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!