首页 > 代码库 > LeetCode:461. Hamming Distance
LeetCode:461. Hamming Distance
1 package BitManipulation; 2 //Question 461. Hamming Distance 3 /* 4 The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 5 Given two integers x and y, calculate the Hamming distance. 6 Note: 7 0 ≤ x, y < 231. 8 Example: 9 Input: x = 1, y = 4 10 Output: 2 11 Explanation: 12 1 (0 0 0 1) 13 4 (0 1 0 0) 14 ↑ ↑ 15 The above arrows point to positions where the corresponding bits are different. 16 */ 17 public class hammingDistance461 { 18 public static int hammingDistance(int x, int y) { 19 int count=0; 20 while(x>0|y>0){ 21 count+=(x&1)^(y&1); 22 x=x>>1; 23 y=y>>1; 24 } 25 return count; 26 } 27 //test 28 public static void main(String[] args){ 29 int x=1; 30 int y=4; 31 System.out.println(hammingDistance(x,y)); 32 } 33 34 //study the solution of other people 35 //example1:use Integer.bitCount 36 public static int hammingDistance1(int x, int y) { 37 return Integer.bitCount(x ^ y); 38 } 39 //example2:xor = (xor) & (xor-1) 40 //4(100),1(001)->101&100=100->100&011=000 41 //1000001001这样中间的0可以一步直接跳过,机智! 42 public int hammingDistance2(int x, int y) { 43 int count = 0; 44 for(int xor = x^y; xor != 0; xor = (xor) & (xor-1)) count++; 45 return count; 46 } 47 }
LeetCode:461. Hamming Distance
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。