在 C++ 中具有更多位集合的下一個更大整數


我們得到一個數字 n,我們必須找到大於 n 的數字,其二進位制表示中比 n 多一個集合位。

二進位制表示中的數字 1 稱為集合位。

我們來看一個例子。

輸入

124

輸出

125

演算法

  • 初始化數字n

  • 編寫一個函式以獲取集合位數。

  • 使用 n + 1初始化迭代變數。

  • 編寫一個無限迴圈。

    • 檢查大於n的數字的集合位數。

    • 找到數字時返回該數字。

實現

以下是上述演算法在 C++ 中的實現

#include <bits/stdc++.h>
using namespace std;
int getSetBitsCount(int n) {
   int count = 0;
   while (n) {
      if (n % 2 == 1) {
         count += 1;
      }
      n /= 2;
   }
   return count;
}
int getNextGreaterElementWithSameSetBits(int n) {
   int setBitsCount = getSetBitsCount(n);
   int i = n + 1;
   while (true) {
      if (setBitsCount + 1 == getSetBitsCount(i)) {
         return i;
      }
      i += 1;
   }
}
int main() {
   int n = 124;
   cout << getNextGreaterElementWithSameSetBits(n) << endl;
   return 0;
}

輸出

如果您執行以上程式碼,您將獲得以下結果。

125

更新於:2021 年 10 月 25 日

106 次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.