LeetCode Top 100 Liked Questions 461. Hamming Distance (Java版; Easy)

welcome to my blog

LeetCode Top 100 Liked Questions 461. Hamming Distance (Java版; Easy)

题目描述

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 < 2^31.

Example:

Input: x = 1, y = 4

Output: 2

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

第一次做; 两数异或之后, 再统计1的个数a&(a-1); 注意异或和与的符号别弄错了!!!

class Solution {
    public int hammingDistance(int x, int y) {
        int res = x ^ y;
        int count=0;
        while(res != 0){
            count++;
            //将最右侧的1置零
            res = res & (res-1);
        }
        return count;
    }
}

你可能感兴趣的:(LeetCode,Hot100,LikedQuestions,LeetCode,LeetCode,java)