LC461(HOT100). 汉明距离 (位运算-简单)

LC461 汉明距离

题目:两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。给出两个整数 x 和 y,计算它们之间的汉明距离。
        如:输入  x = 1, y = 4  输出 2    因为 1(0 0 0 1)  4(0 1 0 0)  第二位和最后一位不同 所以累计汉明距离为2
思路:位运算
复杂度: 时间复杂度O(1)   空间复杂度O(1)

PS:该问题的思想与问题数组中数字出现的次数 (Offer 56 - I)的一小部分相同。

'''
    题目:两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。给出两个整数 x 和 y,计算它们之间的汉明距离。
        如:输入  x = 1, y = 4  输出 2    因为 1(0 0 0 1)  4(0 1 0 0)  第二位和最后一位不同 所以累计汉明距离为2
    思路:位运算  我们知道位运算 & 有过滤的功能。 所以可以将x y与 取值分别是(0001、0010、0100……)(可以用左移来实现)的m进行与运算,结果不同则计数加1,最终返回计数结果。
         简化:既然是分别相与之后进行判断,则可以先使用异或位运算算出一个包含不同位表示为1的值,然后再进行相与。 为了方便控制迭代范围,可以将异或结果右移,而m不变。
    复杂度: 时间复杂度O(1) (在 Python 和 Java 中 Integer 的大小是固定的,处理时间也是固定的。)   空间复杂度O(1)
'''
def hammingDistance(x, y):
    m, count = 1, 0
    n = x ^ y  # 按位异或
    while n:
        if n & m == 1:
            count += 1
        n >>= 1
    return count

路虽远,行则将至。事虽难,做则必成 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure! Here's your code with comments added: ```matlab F = zeros(length(z), 1); % Initialize the F vector with zeros for i = 1:length(z) % Define the Phi function using anonymous function Phi = @(theta, R, r) (z(i) + lc - lm) .* r.R .(R - r.sin(theta)) ./ ... ((R.^2 + r.^2 - 2*R.*r.*sin(theta)).sqrt(R.^2 + r.^2 + (z(i) + lc - lm).^2 - 2*R.*r.*sin(theta))) + ... (z(i) - lc + lm) .* r.R .(R - r.sin(theta)) ./ ... ((R.^2 + r.^2 - 2*R.*r.*sin(theta)).sqrt(R.^2 + r.^2 + (z(i) - lc + lm).^2 - 2*R.*r.*sin(theta))) + ... (z(i) + lc + lm) .* r.R .(R - r.sin(theta)) ./ ... ((R.^2 + r.^2 - 2*R.*r.*sin(theta)).sqrt(R.^2 + r.^2 + (z(i) + lc + lm).^2 - 2*R.*r.*sin(theta))) + ... (z(i) - lc - lm) .* r.R .(R - r.sin(theta)) ./ ... ((R.^2 + r.^2 - 2*R.*r.sin(theta)).sqrt(R.^2 + r.^2 + (z(i) - lc - lm).^2 - 2*R.*r.sin(theta))); % Calculate the value of F(i) using the integral3 function F(i) = BrNI / (4 * lc * (Rc - rc)) * integral3(Phi, 0, 2*pi, rc, Rc, rm, Rm); end ``` This code calculates the values of the vector `F` using a loop. The `Phi` function is defined as an anonymous function that takes `theta`, `R`, and `r` as input parameters. It performs a series of calculations and returns a value. The integral of `Phi` is then calculated using the `integral3` function. The result is stored in the corresponding element of the `F` vector. Please note that I have made some assumptions about the variables and functions used in your code since I don't have the complete context. Feel free to modify or clarify anything as needed.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值