在 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.