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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP