在 C++ 中具有相同数量的设置位的下一个更高的数字

在本教程中,我们将编写一个程序来查找下一个具有更多设置位的更大整数。

让我们看看解决问题的步骤。

  • 初始化数字n。

  • 编写一个函数来获取设置位数的计数。

  • n + 1初始化迭代变量

  • 写一个无限循环。

    • 检查与 n 的设置位数相等的数字的设置位数。

    • 找到后返回号码。

示例

让我们看看代码。

#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 == getSetBitsCount(i)) {
         return i;
      }
      i += 1;
   }
}
int main() {
   int n = 124;
   cout << getNextGreaterElementWithSameSetBits(n) << endl;
   return 0;
}
输出结果

如果你运行上面的代码,那么你会得到下面的结果。

143

结论

如果您对本教程有任何疑问,请在评论部分提及。