LeetCode 089 Gray Code

本文介绍了一种生成灰码序列的方法,灰码是一种特殊的二进制数系统,相邻两个数只有一位不同。文中提供了递增位数时灰码序列的生成规律,并附带了Java实现代码。
题目


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,写出n位的格雷码。


思路


1 先写出n=1----n=4的格雷码,开始找规律。

2 发现不管n等于几,开头总是一样的;n越大,后面增加的数字越多。

3 发觉每次n后半部分的数字都是前半部分数字倒序后+固定数量的数,这个数是2^n-1,通过观察二进制也能够发现规律。

4 从0到1到2都是如此,所以这是普遍现象,可以完美使用循环。


ps 看到另外一种方法,前提是知道格雷码的计算特点

http://blog.youkuaiyun.com/fightforyourdream/article/details/14517973


代码


public class Solution {
    public ArrayList<Integer> grayCode(int n) {
        ArrayList<Integer> ans = new ArrayList<Integer>();
        if(n<0){
            return ans;
        }
        ans.add(0);
        int s =0;
        while(s<n){
            int maxs = 1<<s;
            for(int i=ans.size()-1;i>=0;i--){
                int temp = ans.get(i);
                ans.add(temp+maxs);
            }
            s++;
        }
        return ans;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值