Solution by RikeVoltz


  • 0
    R

    Approach #1 XOR Solution [Accepted]

    Task
    Find the Hamming distance between two integers.

    Idea of solution
    Cast input integers to bitsets and use XOR operation. By definition of XOR operation it returns false if operands are the same and true otherwise. After XOR operation we'll get another bitset with amount of ones which is the same as Hamming distance. After that we'll use count() method of bitset to get the final result.

    C++ algorithm

    class Solution {
    public:
        int hammingDistance(int x, int y) {
            bitset<32>xbit(x);
            bitset<32>ybit(y);
            bitset<32>zbit(xbit^ybit);
            return zbit.count();
        }
    };
    

    In another point of view we can use 'one-line solution':

    class Solution {
    public:
        int hammingDistance(int x, int y) {
            return (bitset<32>(x)^bitset<32>(y)).count();
        }
    };
    

    Complexity Analysis

    • Time complexity : O(N_b), where N_b is the amount of bits in input numbers.
    • Space complexity : O(N_b), because we just use 3 bitsets.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.