通过重新排列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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短