[LeetCode] Hamming Distance(二进制中有多少个1)+ Number Complement(补码)

啊,又是好久没来了!

最近又开始刷leetcode,发现题目多了不少。还是从基础开始做吧。


这里是两道关于位运算的题。

1. Hamming Distance

题目链接在此


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.

就是数一下两个二进制数之间有位数有区别。很简单,先异或,再数有多少个1。

输多少个1那一步,我写的这篇博客有。


这里是我在不记得大神的做法的情况下,自己写的(3ms):

class Solution {
public:
	int hammingDistance(int x, int y) {
		int a = x ^ y;

		int count = 0;

		while (a != 0) {
			count += (a & 1); 
			a >>= 1;
		}

		return count;
	}
};

2. Number Complement

题目链接在此


Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.

Example 1:

Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
补码定义为二进制每位都翻转后得到的数字。

这是我写的,就是先算出这个数的二进制有多少位,然后用这么多位的1跟他做异或。比如2的二进制是10,有两位, 就拿11和10做异或,得到01。显然比较慢:
class Solution {
public:
    int findComplement(int num) {
        int n = num;
        int bits = 0;
        while(n) {
            bits++;
            n >>= 1;
        }
        return num ^ int(pow(2.0, bits) - 1);
    }
};


这是discuss里的大神的做法:
class Solution {
public:
    int findComplement(int num) {
        unsigned mask = ~0;
        while (num & mask) mask <<= 1;
        return ~mask & ~num;
    }
};

例子:
num          = 00000101
mask         = 11111000
~mask & ~num = 00000010


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值