在 C++ 中找到具有 n 個設定位和 m 個未設定位的最大數字


在這個問題中,我們給定兩個整數值,n 和 m。我們的任務是找到在數字的二進位制表示中具有 n 個設定位和 m 個未設定位的最大數字

讓我們舉個例子來理解這個問題

Input : n = 3, m = 1
Output : 14

說明 -

Largest number will have 3 set bits and then 1 unset bit.
(1110)2 = 14

解決方案方法

解決這個問題的一個簡單方法是找到由 (n+m) 個設定位組成的數字。從此數字中,從末尾 (LSB) 關閉 m 個位元。要建立一個具有 (n+m) 個設定位的數字,

$$(1\ll(n+m))-1$$

然後切換 m 位並返回數字。

示例

程式來說明我們解決方案的工作原理

#include <iostream>
using namespace std;
int findlargestNumber(int n, int m){
   int maxNum = (1 << (n + m)) - 1;
   if (m == 0)
      return maxNum;
   int number = (1 << m) - 1;
   return (maxNum ^ number);
}
int main(){
   int n = 5,
   m = 2;
   cout<<"The largest number with "<<n<<" set bits and "<<m<<" unset bits is "<<findlargestNumber(n, m);
   return 0;
}

輸出

The largest number with 5 set bits and 2 unset bits is 124

更新日期: 2022 年 1 月 28 日

131 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.