在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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语