Tạo số mới bằng cách lấy bit xen kẽ từ hai số: bit 0 từ số thứ 2, bit 1 từ số thứ 1, bit 2 từ số thứ 2, bit 3 từ số thứ 1,... (từ LSB).
Ví dụ: n=6 (0110), m=10 (1010). Bit xen kẽ: m0=0, n1=1, m2=1, n3=0 -> 0010 = 2.
Cách làm: Tách bit chẵn của n (vị trí 0,2,4...), bit lẻ của m (vị trí 1,3,5...), OR lại.
Thuật toán
Bước 1: Tạo mask bit chẵn cho n: res_n = 0; count=0; while(n>>count){ if(count%2==1) res_n|=1<>count){ if(count%2==0) res_m|=1<
Ví dụ code
#include <iostream>
using namespace std;
int setEvenBits(int n) {
int res = 0, count = 0;
for (int temp = n; temp > 0; temp >>= 1) {
if (count % 2 == 1) res |= (1 << count);
count++;
}
return n & res;
}
int setOddBits(int m) {
int res = 0, count = 0;
for (int temp = m; temp > 0; temp >>= 1) {
if (count % 2 == 0) res |= (1 << count);
count++;
}
return m & res;
}
int main() {
int n = 12, m = 17;
int result = setEvenBits(n) | setOddBits(m);
cout << result;
return 0;
}
Kết quả
25