在 C++ 中,少於當前整型且具有較少置位數的較小前一整型


在此問題中,我們得到一個整數 n。我們的任務是打印出小於 n 的最大整數,該整數可透過更改該數字的二進位制表示形式的某個設定位來形成。

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

Input: n = 3
Output: 2
Explanation: (3)10 = (011)2
Flipping one set bit gives 001 and 010. 010 is greater i.e. 2.

要解決此問題,我們將必須翻轉最右側的設定位並將其變為零,這將建立將數字的一個位翻轉找到的最大可能的數字,該數字小於 n。

演示如何實現我們解決方案的程式,

示例

 現場演示

#include<iostream>
#include<math.h>
using namespace std;
int returnRightSetBit(int n) {
   return log2(n & -n) + 1;
}
void previousSmallerInteger(int n) {
   int rightBit = returnRightSetBit(n);
   cout<<(n&~(1<<(rightBit - 1)));
}
int main() {
   int n = 3452;
   cout<<"The number is "<<n<<"\nThe greatest integer smaller than the number is : ";
   previousSmallerInteger(n);
   return 0;
}

輸出

The number is 3452
The greatest integer smaller than the number is : 3448

更新日期:03-Feb-2020

109 已檢視

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.