在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP