frendguo's blog

【LeetCode】476. Number Complement

原文地址:https://leetcode.com/problems/number-complement/#/description

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.

 看到这个题,首先想到的就是用异或运算,将所有位取反。于是就需要找到给定数值的最高位了,找到数据的最高位后,通过一位一位的异或运算,就能实现要求。

于是我写出了这个烂代码:

static int FindNumberComplement(int num)
{
	if (num == 1) return 0;
	int n = 0x40000000;
	int tmp = 0;
	do
	{
		tmp = num & n;
		n >>= 1;
	}while (tmp == 0);
	n <<= 1;
	while (n != 0)
	{
		num ^= n;
		n >>= 1;
	}

	return num;
}

然后想着能不能有优化方法,于是试了下从低位开始的,果然好看多了,效率也高了:

static int FindNumberComplement2(int num)
{
	int mask = 1;
	while (mask < num)
	{
		mask = (mask << 1) | 1;
	}
	return num ^ mask;
}

Happy Coding!o(* ̄▽ ̄*)o

Add comment

Loading