通过在C ++中的极端位置交换位来最大化给定的无符号数
问题陈述
给定一个数字,可以通过在其极端位置(即第一个和最后一个位置,第二个和第二个最后一个位置)交换位来最大化它。
如果输入数字为8,则其二进制表示为-
00000000 00000000 00000000 00001000
在交换极端位置的位后,数字变为-
00010000 00000000 00000000 00000000 and its decimal equivalent is: 268435456
算法
1. Create a copy of the original number 2. If less significant bit is 1 and more significant bit is 0 then swap the bits in the bit from only, continue the process until less significant bit’s position is less than more significant bit’s position 3. Return new number
示例
#include <bits/stdc++.h>
#define ull unsigned long long
using namespace std;
ull getMaxNumber(ull num){
ull origNum = num;
int bitCnt = sizeof(ull) * 8 - 1;
int cnt = 0;
for(cnt = 0; cnt < bitCnt; ++cnt, --bitCnt) {
int m = (origNum >> cnt) & 1;
int n = (origNum >> bitCnt) & 1;
if (m > n) {
int x = (1 << cnt | 1 << bitCnt);
num = num ^ x;
}
}
return num;
}
int main(){
ull num = 8;
cout << "Maximum number = " << getMaxNumber(num) << endl;
return 0;
}输出结果
当您编译并执行上述程序时。它生成以下输出-
Maximum number = 268435456