Hello, everyone.
I'm not a CS major, but I just nosing around CS department pages and occasionally try to solve the problems that are posted.
I guess some of you are familiar with the "twiddling bits" problem.
Like creating an AND function with just ~ and |.
Well, I'm stumped on this one.
Code:
/*
* evenBits - return word with all even-numbered bits set to 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 8
* Rating: 2
*/
int evenBits(void) {
return 2;
}
My compiler has 32bit integers, so even allowing that max ops is 16 and not 8, I can't seem to solve it without using some 32 operands.
The site said I'm not supposed to use loops but just to make the code shorter, here's what I did.
Code:
int evenBits(void) {
int i, j;
i = 0;
for(j = 31; j > 0; j -= 2)
i |= (1 << j);
return i;
}
Counting the times I use | and <<, it's about 32 times, I guess.
Is there a way to do this with just 16 (or 8)?