给定一个无符号数,找到可以通过使用给定无符号数位形成的最大数
如果输入数字为8,则其二进制表示为-
00000000000000000000000000001000
为了最大化它,请将MSB设置为1。然后数字变为2147483648,其二进制表示为-
10000000000000000000000000000000
1. Count number of set bits in the binary representation of a given number 2. Find a number with n least significant set bits 3. shift the number left by (32 – n)
#include <bits/stdc++.h> using namespace std; unsigned getMaxNumber(unsigned num){ int n = __builtin_popcount(num); if (n == 32) { return num; } unsigned result = (1 << n) - 1; return (result << (32 - n)); } int main(){ unsigned n = 8; cout << "Maximum number = " << getMaxNumber(n) << endl; return 0; }
输出结果
当您编译并执行上述程序时。它生成以下输出-
Maximum number = 2147483648