#include <stdio.h>
/*
* bitXor - x^y using only ~ and &
* Example: bitXor(4, 5) = 1
* Legal ops: ~ &
* Max ops: 14
* Rating: 2
*/
int bitXor(int x, int y)
{
return ~((~((~y)&x))&(~((~x)&y)));
}
/*
* bitAnd - x&y using only ~ and |
* Example: bitAnd(6, 5) = 4
* Legal ops: ~ |
* Max ops: 8
* Rating: 1
*/
int bitAnd(int x, int y)
{
return ~((~x)|(~y));
}
/*
* isEqual - return 1 if x == y, and 0 otherwise
* Examples: isEqual(5,5) = 1, isEqual(4,5) = 0
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int isEqual(int x, int y)
{
return !(x ^ y);
}
/*
* isZero - returns 1 if x == 0, and 0 otherwise
* Examples: isZero(5) = 0, isZero(0) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 2
* Rating: 1
*/
int isZero(int x)
{
return !(x!=0);
}
int test_unary(const char *name, int (*f)(int), int value)
{
int result = f(value);
printf("%s(%d) = %d\n", name, value, result);
return result;
}
int test_binary(const char *name, int (*f)(int, int), int x, int y)
{
int result = f(x, y);
printf("%s(%d,%d) = %d\n", name, x, y, result);
return result;
}
#define printpair(x) #x,x
int main()
{
test_binary(printpair(bitXor), 4, 5);
test_binary(printpair(bitAnd), 6, 5);
test_binary(printpair(isEqual), 5, 5);
test_binary(printpair(isEqual), 4, 5);
test_unary(printpair(isZero), 0);
test_unary(printpair(isZero), 5);
return 0;
}
/* my output
bitXor(4,5) = 1
bitAnd(6,5) = 4
isEqual(5,5) = 1
isEqual(4,5) = 0
isZero(0) = 1
isZero(5) = 0
*/