ในปัญหานี้ เราได้รับจำนวนเต็ม 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