在 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

更新於: 24-12-2019

1095 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.