在 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

更新於: 2019 年 12 月 24 日

135 次瀏覽

啟動你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.