이 문제에서는 두 숫자의 대체 비트를 사용하여 숫자를 생성해야 합니다. . 따라서 이 문제에서는 두 번째 숫자의 첫 번째 비트를 사용한 다음 첫 번째 숫자의 두 번째 비트를 사용하고 두 번째 숫자의 세 번째 비트를 다시 사용하고 첫 번째 숫자의 다음 비트를 사용하는 식입니다.
첫 번째부터 두 번째 숫자부터 세 번째 비트, 첫 번째 숫자부터 세 번째 비트 등등.
주제를 더 잘 이해하기 위해 예를 들어 보겠습니다.
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