คำชี้แจงปัญหา
กำหนดช่วง [L, R] ภารกิจคือการค้นหาคู่ (X, Y) โดยที่ L ≤ X
ตัวอย่าง
หาก L =1 และ R =10 ค่าบิตสูงสุดและค่าบิตสูงสุดคือ 8 ซึ่งสามารถเกิดขึ้นได้ดังนี้ −
1000 # Binary representation of 8 Bitwise AND 1001 # Binary representation of 9 ---- 1000 # Final result
อัลกอริทึม
วนซ้ำจาก L ถึง R และตรวจสอบระดับบิตและสำหรับทุกคู่ที่เป็นไปได้และพิมพ์ค่าสูงสุดในส่วนท้าย
ตัวอย่าง
เรามาดูตัวอย่างกัน −
#include <bits/stdc++.h> using namespace std; int getMaxBitwiseAndValue(int L, int R) { int maxValue = L & R; for (int i = L; i < R; ++i) { for (int j = i + 1; j <= R; ++j) { maxValue = max(maxValue, (i & j)); } } return maxValue; } int main() { int L = 1, R = 10; cout << "Maximum value = " << getMaxBitwiseAndValue(L, R) << endl; return 0; }
ผลลัพธ์
Maximum value = 8