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

461. Hamming Distance

时间:2017-01-22 22:40:27      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:targe   个数   turn   output   size   结束   org   min   while   

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

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;
原始代码如下:
 1 class Solution {
 2 public:
 3     int hammingDistance(int x, int y) {
 4         int dis = 0;
 5         while(x && y){
 6             dis += (x & 1) ^ (y & 1);//x&1异或y&1
 7             x >>= 1;//x右移一位
 8             y >>= 1;
 9         }
10         while(x){
11             dis += (x & 1);
12             x >>= 1;
13         }
14         while(y){
15             dis += (y & 1);
16             y >>= 1;
17         }
18         return dis;
19     }
20 };

两个数都不为0的话,比较两个数的最后一位,x&1得到x对应二进制的最后一位,通过异或运算判断最后一位是否相同,不同加1,相同加0.循环结束后只有一个数不为0,另外一个数为0,此时0对应的所有二进制都为0,此时只要计算不为0的数对应二进制1的个数。

改进:上面用了三个while,用一个就够了:

 1 class Solution {
 2 public:
 3     int hammingDistance(int x, int y) {
 4         int dis = 0;
 5         while(x || y){//或运算,只要有一个不为0就进行此循环
 6             dis += (x & 1) ^ (y & 1);
 7             x >>= 1;
 8             y >>= 1;
 9         }
10         return dis;
11     }
12 };

 

改进:显然,只要将x和y异或,得到数对应的二进制位为1的个数即为x和y的汉明距离。

 1 class Solution {
 2 public:
 3     int hammingDistance(int x, int y) {
 4         int count = 0;
 5         int t = x ^ y;
 6         while(t){
 7             count += t & 1;
 8             t >>= 1;
 9         }
10         return count;
11     }
12 };

 

 

461. Hamming Distance

标签:targe   个数   turn   output   size   结束   org   min   while   

原文地址:http://www.cnblogs.com/qinduanyinghua/p/6341493.html

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