Leetcode 89. Gray Code

这篇博客探讨了如何使用 Python 实现 Gray 码的生成算法。Gray 码是一种二进制数字系统,其特点是相邻两个码字之间仅有一位不同。文中详细解释了 Gray 码的定义,并提供了相应的代码示例,展示了如何通过位异或操作生成从 0 到 (2^n)-1 的所有 Gray 码。

Problem

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.

Algorithm

The i-th gray code number is Gi=BixorBi−1G_i = B_i \mathbf{xor} B_{i-1}Gi=BixorBi1, where BiB_iBi is the i-th binary code number.

Code

class Solution:
    def grayCode(self, n: int) -> List[int]:
        gray = []
        for i in range(1<<n):
            gray.append(i^(i>>1))
        
        return gray
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值