通过重新排列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 生日祝福语送老公简短