我完全被困在如何做这个家庭作业问题上,并寻找一两个提示让我继续前进。我仅限于 20 次操作(=
不计入这 20 次)。
我应该填写一个看起来像这样的函数:
/* Supposed to do x%(2^n).
For example: for x = 15 and n = 2, the result would be 3.
Additionally, if positive overflow occurs, the result should be the
maximum positive number, and if negative overflow occurs, the result
should be the most negative number.
*/
int remainder_power_of_2(int x, int n){
int twoToN = 1 << n;
/* Magic...? How can I do this without looping? We are assuming it is a
32 bit machine, and we can't use constants bigger than 8 bits
(0xFF is valid for example).
However, I can make a 32 bit number by ORing together a bunch of stuff.
Valid operations are: << >> + ~ ! | & ^
*/
return theAnswer;
}
我在想也许我可以twoToN
向左移动......直到我以某种方式检查(没有if / else)它比x大,然后向右移动一次......然后用x异或它......和重复?但我只有20个手术!