이 문제에서는 정수 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.
이 문제를 해결하려면 가장 오른쪽에 있는 설정 비트를 뒤집고 0으로 만들어 숫자의 1비트를 뒤집어 찾은 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