LeetCode461 Hamming Distance java The Hamming distance between two integers is the number osoluotion

时间:2023-01-08 15:40:29

题目要求:

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 ≤ xy < 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.

注:该题目没有bug free 

原因在于:创建循环条件的时候没有注意取最大值

public class Solution {
    public int hammingDistance(int x, int y) {
        int step = 0;
        while(Math.max(x, y) != 0) {
            int temple1 = x % 2;
            int temple2 = y % 2;
            if(temple1 != temple2) step++;
            x /= 2;
            y /= 2;
        }
        return step;
    }
}