给定一个一个数,找出二进制表示有相同数量1的最大的和最小的数。

 

分析:首先考虑正数,我们将1尽可能放到高位(除符号位)。对于负数,就稍微复杂一点,因为在我们计算机上,负数是用补码表示的,对于补码,1应该竟可能放到低位(除符号位)。知道这些,就很容写出代码来了,下面是参考代码。

 

#include <iostream>

using namespace std;

// 1的个数
int ones(unsigned int x)
{
	int n = 0;
	while (x)
	{
		if ( x & 1 == 1)
			n ++;
		x >>= 1;
	}
	return n;
}

int max_with_same_bits(int x)
{
	if (x == -1)
		return -1;
	// 1's
	int n = ones(x);
	x = 0;
	for (int i = 30; i > 0 && n > 0; i--, n--)
		x |= 1 << i;
	return x;
}

int min_with_same_bits(int x)
{
	if (x == 0)
		return 0;
	// 1's
	int n = ones(x);
	x = 0x80000000;
	for (int i = 0; i < n - 1; i++)
		x |= 1 << i;
	return x;
}

int main()
{
	int x = 7;
	cout << x << endl;
	cout << min_with_same_bits(x) <<endl;
}

相关文章:

  • 2021-10-07
  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-19
  • 2021-07-24
猜你喜欢
  • 2021-08-25
  • 2021-06-11
  • 2022-12-23
  • 2021-12-14
  • 2021-11-12
  • 2022-01-08
  • 2021-10-19
相关资源
相似解决方案