在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP