Print x or y using bit

Given three 32-bit integers x, y, and b, return x if b is 1 and y if b is 0, using only mathematical or bit operations. You can assume b can only be 1 or 0.

Example:

Input:  x = 10, y = 24, b = 1
Output: 10

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int bitOpertion(int xint yint b)
{
    b = -b;

    return (x & b) | (y & ~b);
}

int main()
{
    int x = 10y = 24;
    int b = 1;

    cout << bitOpertion(xyb);
    return 0;
}


No comments:

Post a Comment