Leetcode | Hamming Distance

461. Hamming Distance

class Solution {
public:
    int hammingDistance(int x, int y) {
        /*
        // caculate from first digit
        int n = x ^ y, ns = 0;
        while (n) {
            ++ ns;
            n &= n - 1;
        }
        */
        // caculate from last digit
        int n = x ^ y, ns = 0;
        while (n){
            ns += n & 1;
            n = n >> 1;
        }
        return ns;
    }
};

3ms/E

477. Total Hamming Distance

  • C++ solution with little hit| O(n), bitwise
    • Compared to calculate every pair of numbers, processing with every digit from all numbers is clever.
    • Since Hamming distance will be added when two numbers are different, this problem turn to be “counting the number of cases that pari numbers are different in every digit.”
    • So for binary numbers, what we should do is counting how many 1 existing in this digit, and count(0) = nums.size() - count(1).
    • Then different pairs exists when two numbers are from different sets that total += count(1) * count(0).
class Solution {
public:
    int totalHammingDistance(vector<int>& nums) {
        int ans = 0, ns, t = 0;
        if (nums.size()<2) return 0;        
        while (t < nums.size()){
            ns = 0;
            t = 0;
            for (int i =0; i < nums.size(); i++){
                //caculate from the last digit
                ns += nums[i]&1;
                nums[i] = nums[i] >> 1;
                if (nums[i]==0) t++;
            }
            ans += ns * (nums.size()-ns);
        }
        return ans;
    }
};

59ms/M

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值