leetCode(Using C)——461. Hamming Distance

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lovefengruoqing/article/details/79080745

Description

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:

0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

The above arrows point to positions where the corresponding bits are different.

If you want to solve the problem, you can visite the web site.click me

Solution:

#define MAXSIZE 32
int hammingDistance(int x, int y) {
    int stack1[MAXSIZE],top1=-1;
    int stack2[MAXSIZE],top2=-1;
    int dis;

    while(x>0){
        stack1[++top1] = x%2;
        x /= 2;
    }


    while(y>0){
        stack2[++top2] = y%2;
        y /= 2;
    }

    dis=0;
    while(top1>top2){
        if(stack1[top1--]==1){
            dis++;
        }
    }

    while(top2>top1){
        if(stack2[top2--]==1){
            dis++;
        }
    }

    while(top1>-1&&top2>-1){
        if(stack1[top1--]!=stack2[top2--]){
            dis++;
        }
    }

    return dis;
}

猜你喜欢

转载自blog.csdn.net/lovefengruoqing/article/details/79080745