Leetcode 461. 汉明距离

1、问题分析

题目链接:https://leetcode-cn.com/problems/hamming-distance/
  本质上就是一个进制转换问题。代码我已经进行了详细的注释,理解应该没有问题,读者可以作为参考,如果看不懂(可以多看几遍),欢迎留言哦!我看到会解答一下。

2、问题解决

  笔者以C++方式解决。

#include "iostream"

using namespace std;

#include "algorithm"
#include "vector"
#include "queue"
#include "set"
#include "map"
#include "string"
#include "stack"

class Solution {
public:
    int hammingDistance(int x, int y) {
        // 定义 1 的个数
        int num = 0;
        // 获取汉明距离 10 进制表示
        int result = x ^y;
        // 将 10进制 转化成 2进制
        while (result > 0) {
            // 遇到 1 则个数 +1
            if (result % 2 == 1) {
                num++;
            }
            // 不断缩小 result 值
            result /= 2;
        }

        // 返回结果
        return num;
    }
};

int main() {

    Solution *pSolution = new Solution;
    int i = pSolution->hammingDistance(1, 4);
    cout << i << endl;
    system("pause");
    return 0;
}

运行结果

在这里插入图片描述

有点菜,有时间再优化一下。

3、总结

  难得有时间刷一波LeetCode, 这次做一个系统的记录,等以后复习的时候可以有章可循,同时也期待各位读者给出的建议。算法真的是一个照妖镜,原来感觉自己也还行吧,但是算法分分钟教你做人。前人栽树,后人乘凉。在学习算法的过程中,看了前辈的成果,受益匪浅。
感谢各位前辈的辛勤付出,让我们少走了很多的弯路!
哪怕只有一个人从我的博客受益,我也知足了。
点个赞再走呗!欢迎留言哦!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章