411 - 格雷编码

2017.10.20

格雷编码,最主要的就是要了解编码产生的过程。

这段是抄别人的,哈哈哈:如n=2时,格雷码为00,01,11,10.如需生成n=3的格雷码只需先将原序列高位加0变成000,001,011,010,再将原序列在高位加1并逆向添加到刚才生成的序列尾部,即000,001,011,010,110,111,101,100。也就是说,n+1位元格雷码是基于n位元格雷码产生的。

public class Solution {
    /*
     * @param n: a number
     * @return: Gray code
     */
 	public List<Integer> grayCode(int n) {
        // write your code here
		List<Integer> res = new LinkedList<>();
		if(n == 0){
		    res.add(0);
			return res;
		}
		if(n == 1){
		    res.add(0);
			res.add(1);
			return res;
		}
		List<Integer> list = grayCode(n-1);
		for(int i = 0 ;i < list.size(); i++){
			res.add(list.get(i));
		}
		int add = (int)Math.pow(2, n-1);
		for(int i = list.size() - 1; i >= 0; i--){
			res.add(list.get(i) + add);
		}
		return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值