下一个更大的整数在 C++ 中具有更多的设置位
在本教程中,我们将编写一个程序来查找下一个具有更多设置位的更大整数。
让我们看看解决问题的步骤。
初始化数字n。
编写一个函数来获取设置位数的计数。
用n+1初始化迭代变量。
写一个无限循环。
检查大于n的数字的设置位数。
找到后返回号码。
示例
让我们看看代码。
#include输出结果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
结论
如果您对本教程有任何疑问,请在评论部分提及。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短