[LeetCode] Hamming Distance 汉明距离

声明:原题目转载自LeetCode,解答部分为原创

Problem :

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.


Solution :

        思路 : 好久没做C++编程题了,先来道简单的练练手。对二进制表示数来说,汉明距离是指两个二进制数在对应位上的数不同(即对应

位置上,二进制数x、y的数分别为1、0)的位数之和。例如,对于(101) 和(000),第一位和第三位不同,则汉明距离为2。

        计算两个二进制数的异或,记为z,转换为二进制数,记录位上数值为1的位数之和并输出。

代码如下:

#include
   
   
    
    
using namespace std;

int num_of_bits[35] = {0};
class Solution {
public:
    int hammingDistance(int x, int y) {
//    	int num_of_bits[35] = {0};
    	int exclusive_or = x ^ y;
    	
    	int index = 31;
    	while(exclusive_or != 0)
    	{
    		int temp = exclusive_or / 2;
    		int leave = exclusive_or - temp * 2;
			num_of_bits[index --] = leave;
			exclusive_or = temp; 
		}
		
		int num = 0;
		for(int i = index; i < 32 ; i ++)
		{
			if(num_of_bits[i])
				num ++;
		}
		return num;
    }
};

int main(){
	Solution text_1;
	int x, y;
	cout << "Please input the text number (x, y) :" << endl;
	cin >> x >> y;
	cout << "The Hamming Distance of (1, 4) is :"<< endl;
	cout << text_1.hammingDistance(x, y) << endl;
	return 0;
}
   
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值