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

【LeetCode】Gray Code

时间:2014-12-05 16:49:10      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   strong   

Gray Code

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.

 

列出前几个格雷码观察规律:

n=3

0 0 0 

0 0 1

0 1 1

0 1 0

1 1 0

1 1 1

1 0 1

1 0 0

可以发现,最右边第0位是以0110循环,第1位是以00111100循环……

由此可知,第j位在[2j, 2j+2j+1)是1,其余为0进行循环。每个循环段包含的格雷码总数为2j+2

因此对于第i个格雷码的第j位,需要根据i判断落在第j循环段的0位还是1位。

将i从左往右扫一遍,确定0/1后左移,即可。

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> result;
        for(int i = 0; i < pow(2.0,n); i ++)
        {//2^n numbers
            int value = 0;
            for(int j = n-1; j >= 0; j --)
            {//jth digit from right to left
                int divisor = pow(2.0, j+2);
                int r = i%divisor;
                if(r >= pow(2.0, j) && r < pow(2.0, j)+pow(2.0, j+1))
                    value += 1;
                if(j == 0)
                    break;
                value <<= 1;
            }
            result.push_back(value);
        }
        return result;
    }
};

bubuko.com,布布扣

 

【LeetCode】Gray Code

标签:style   blog   http   io   ar   color   sp   for   strong   

原文地址:http://www.cnblogs.com/ganganloveu/p/4146821.html

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