461. Hamming Distance

461. Hamming Distance

 
Question Editorial Solution
  My Submissions
  • Total Accepted: 7016
  • Total Submissions: 9553
  • Difficulty: Easy
  • Contributors:Samuri

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.
Tips:很简单的一道位操作的题目,将整型转成二进制(具体怎么转我们不需要关心,计算机底层就是用二进制存储的),按位比较;主要还是要了解java中的位操作&,以及位移>>操作。
public class Solution {
    public int hammingDistance(int x, int y) {
         int sum=0;
		 while(x>0 || y>0)
		 {
			 int x_=x & 1;
		     int y_=y & 1;


		        if((x_^y_)==1)
		        	sum++;
		        y=y>>1;
		        x=x>>1;
		 }
	    return sum ;   
    }
}

你可能感兴趣的:(Leetcode)