Is this faster than xor methods?


  • 0

    I wrote this and it used 3 ms in 149 runs:

    int hammingDistance(int num1, int num2)
    {
    int count = 0;
    while (num1 != 0 || num2 != 0)
    {
    if ((num1 & 1) != (num2 & 1))
    count++;
    num1 >>= 1;
    num2 >>= 1;
    }
    return count;
    }

    The xor method I tried used 6 ms in 149 runs:

    int hammingDistance(int x, int y){
    int xorxy = x ^ y;
    int count = 0;
    while (xorxy)
    {
    if (xorxy & 1)
    count++;
    xorxy >>= 1;
    }
    return count;
    }


Log in to reply
 

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