Leetcode 461. 漢明距離

一、問題分析

題目連接:https://leetcode-cn.com/problems/hamming-distance/
  本質上就是一個進制轉換問題。代碼我已經進行了詳細的註釋,理解應該沒有問題,讀者能夠做爲參考,若是看不懂(能夠多看幾遍),歡迎留言哦!我看到會解答一下。ios

二、問題解決

  筆者以C++方式解決。web

#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;
}

運行結果算法

在這裏插入圖片描述

有點菜,有時間再優化一下。svg

三、總結

  可貴有時間刷一波LeetCode, 此次作一個系統的記錄,等之後複習的時候能夠有章可循,同時也期待各位讀者給出的建議。算法真的是一個照妖鏡,原來感受本身也還行吧,可是算法分分鐘教你作人。前人栽樹,後人乘涼。在學習算法的過程當中,看了前輩的成果,受益不淺。
感謝各位前輩的辛勤付出,讓咱們少走了不少的彎路!
哪怕只有一我的從個人博客受益,我也滿足了。
點個贊再走唄!歡迎留言哦!學習