使用C ++中给定数字的设置位的最小数字
问题陈述
给定无符号数,请使用给定无符号数的位找到可以形成的最小数。
示例
如果输入=10,则答案为3
10的二进制表示形式是1010,带有2个置位的最小数字形式是0011,即3
算法
1. Count the number of set bits. 2. (Number of set bits) ^ 2 – 1 represents the minimized number)
示例
#include <bits/stdc++.h>
using namespace std;
int getSetBits(int n) {
int cnt = 0;
while (n) {
++cnt;
n = n & (n - 1);
}
return cnt;
}
int getMinNumber(int n){
int bits = getSetBits(n);
return pow(2, bits) - 1;
}
int main() {
int n = 10;
cout << "Minimum number = " << getMinNumber(n) << endl;
return 0;
return 0;
}当您编译并执行上述程序时。它产生以下输出
输出结果
Minimum number = 3