461. Hamming Distance(python+cpp)

本文详细介绍了计算两个整数间汉明距离的多种方法,包括使用异或运算简化计算过程,以及在Python和C++中的具体实现代码。通过对比两个数字的二进制位,找出不同位的数量,即为汉明距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

The Hamming distance between two integers is the number of positions
at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note: 0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

The above arrows point to positions where the corresponding bits are
different.

解释:
可以用暴力对比法,在对比之前先把两个数字的二进制数的长度变成一致的(前面补0,在python中可以用str.zfill(len)函数),事实上,求汉明距离就是求两个数字异或后的结果中1的个数~用异或可以简化求解
python代码(zfill法):

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        if x==y:
            return 0 
        x=bin(x)[2:]
        y=bin(y)[2:]
        x=x.zfill(max(len(x),len(y)))
        y=y.zfill(max(len(x),len(y)))
        count=0
        for i in range(len(x)):
            if x[i]!=y[i]:
                count+=1
        return count

python 代码(异或法):

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x^y).count('1')
                    

c++代码(异或法),c++中统计异或结果中的1的个数不想python那么方便(因为python的二进制实际上是一个字符串):

class Solution {
public:
    int hammingDistance(int x, int y) {
        int n =x^y;
        int dist=0;
        while(n)
        {
            dist+=1;
            n&=n-1;
        }
        return dist;
    }
};

总结:
c++中,求二进制中1的个数
while (n) {
++dist;
n &= n - 1;
}
可以看到n&(n-1)这个操作是将n原来的最右边的1变为0了。
重复操作,有多少个1,这个操作就可以执行多少次。

#include <opencv2/opencv.hpp> #include <opencv2/features2d.hpp> #include <opencv2/calib3d.hpp> #include <iostream> using namespace cv; using namespace std; int main() { // 1. 加载左右图像 Mat imgLeft = imread("left.jpg"); Mat imgRight = imread("right.jpg"); if (imgLeft.empty() || imgRight.empty()) { cerr << "Error: Could not load image files!" << endl; return -1; } // 2. 检测特征点和计算描述子 Ptr<Feature2D> detector = ORB::create(); vector<KeyPoint> keypoints1, keypoints2; Mat descriptors1, descriptors2; detector->detectAndCompute(imgLeft, noArray(), keypoints1, descriptors1); detector->detectAndCompute(imgRight, noArray(), keypoints2, descriptors2); // 3. 特征匹配 Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce-Hamming"); vector<DMatch> matches; matcher->match(descriptors1, descriptors2, matches); // 4. 筛选优质匹配点 vector<DMatch> goodMatches; double minDist = 100, maxDist = 0; for (auto m : matches) { if (m.distance < minDist) minDist = m.distance; if (m.distance > maxDist) maxDist = m.distance; } for (auto m : matches) { if (m.distance <= max(2 * minDist, 30.0)) { goodMatches.push_back(m); } } // 5. 提取匹配点坐标 vector<Point2f> points1, points2; for (auto m : goodMatches) { points1.push_back(keypoints1[m.queryIdx].pt); points2.push_back(keypoints2[m.trainIdx].pt); } // 6. 计算基础矩阵F Mat F = findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99); // 7. 计算核线校正变换 Mat H1, H2; stereoRectifyUncalibrated(points1, points2, F, imgLeft.size(), H1, H2); // 8. 应用校正变换 Mat imgLeftRect, imgRightRect; warpPerspective(imgLeft, imgLeftRect, H1, imgLeft.size()); warpPerspective(imgRight, imgRightRect, H2, imgRight.size()); // 9. 显示结果 Mat canvas; hconcat(imgLeftRect, imgRightRect, canvas); // 绘制水平线验证核线对齐 for (int i = 0; i < canvas.rows; i += 30) { line(canvas, Point(0, i), Point(canvas.cols, i), Scalar(0, 255, 0), 1); } imshow("Rectified Images (Uncalibrated)", canvas); imwrite("rectified_uncalibrated.jpg", canvas); waitKey(0); return 0; }这个代码对吗
最新发布
07-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值