码迷,mamicode.com
首页 > 其他好文 > 详细

位运算(1)——Hamming Distance

时间:2017-05-25 13:23:38      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:位运算   problems   href   input   blank   gdi   运算   out   不同   

https://leetcode.com/problems/hamming-distance/#/description

输入:两个整数x,y,且0 ≤ x, y < 231

输出:x,y的二进制表示,不同的有几位。

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.

 1 public class Solution {
 2     public int hammingDistance(int x, int y) {
 3         int count = 0;
 4         for(int i=0; i<32; i++) {
 5             if((x & 1) != (y & 1)) {
 6                 count++;
 7                 x = x >> 1;
 8                 y = y >> 1;
 9             } else {
10                 x = x >> 1;
11                 y = y >> 1;
12             }
13         }
14         return count;
15     }
16 }

 

位运算(1)——Hamming Distance

标签:位运算   problems   href   input   blank   gdi   运算   out   不同   

原文地址:http://www.cnblogs.com/-1307/p/6902990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!