在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP