通过重新排列C ++中的位来最大化数量
问题陈述
给定一个无符号数,找到可以通过使用给定无符号数位形成的最大数
如果输入数字为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
热门推荐
3 破五祝福语简短的
10 幽默祝福语押韵简短
11 周一祝福语简短精辟
12 鼠年同事祝福语简短创意
13 交接同事退休祝福语简短
14 女方出嫁周年祝福语简短
15 完成预算祝福语简短精辟
16 狗年同事拜年祝福语简短
17 送女儿礼物祝福语简短
18 同事生日祝福语简短独特