使用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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短