ในปัญหานี้ เราต้อง สร้างตัวเลขโดยใช้บิตสำรองของตัวเลขสองตัว . ดังนั้นในปัญหานี้ เราจะใช้บิตแรกจากหมายเลขที่สอง จากนั้นบิตที่สองจากตัวแรก บิตที่สามอีกครั้งจากหมายเลขที่สองและหลังจากนั้นเป็นต้นมา
จากตัวแรก ตัวที่ 3 อีกครั้งจากตัวเลขที่สอง เริ่มจากตัวแรกไปเรื่อยๆ
มาดูตัวอย่างเพื่อทำความเข้าใจหัวข้อกันดีกว่า
Input : n = 6 m = 10 Output : 2 Explanation : Bits representation of 6 = 0110 Bit representation of 10 = 1010 0 1 1 0 ^ ^ 1 0 1 0 ^ ^ = 0 0 1 0 = 2
จากตัวอย่างนี้ มีจุดชัดเจนว่าเราต้องทำอะไรเพื่อแก้โค้ด โดยทั่วไป วิธีแก้ไขคือนำบิตสำรองจากตัวเลขที่เริ่มต้นจาก LSB ของหมายเลขที่สอง
ในการแก้ปัญหานี้ วิธีที่เป็นไปได้วิธีหนึ่งคือการหาเซตคู่ของตัวเลขแรก n แล้วหาชุดบิตคี่ของตัวเลขที่สอง m และส่งคืน ระดับบิต OR ของทั้งสอง
อัลกอริทึม
Step 1 : For n find the value of set even bits. Step 2 : For m find the value of set odd bits. Step 3 : Calculate the result = set even bits of n | set odd bits of m. Step 4: Print the value of result.
ตัวอย่าง
#include <iostream>
using namespace std;
int setevenbits(int n) ;
int setoddbits(int m) ;
int main(){
int n = 12;
int m = 17;
int setn = setevenbits(n);
int setm = setoddbits(m);
int result = ( setn | setm );
cout<<result;
return 0;
}
int setevenbits(int n){
int temp = n;
int count = 0;
int res = 0;
for (temp = n; temp > 0; temp >>= 1) {
if (count % 2 == 1)
res |= (1 << count);
count++;
}
return (n & res);
}
int setoddbits(int m){
int count = 0;
int res = 0;
for (int temp = m; temp > 0; temp >>= 1) {
if (count % 2 == 0)
res |= (1 << count);
count++;
}
return (m & res);
} ผลลัพธ์
25