1.用~和&运算实现异或(^)操作
//*
* bitXor - x^y using only ~ and &
* Example: bitXor(4, 5) = 1
* Legal ops: ~ &
* Max ops: 14
* Rating: 1
*/
可以参考一下德·摩根律
int bitXor(int x, int y) {
return ~(~x&~y)&~(x&y);
}
2.求二进制补码最小值
/*
* tmin - return minimum two's complement integer
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 4
* Rating: 1
*/
int tmin(void) {
return 1<<31;
}
3.判断一个数是否为补码表示的最大值
/*
* isTmax - returns 1 if x is the maximum, two's complement number,
* and 0 otherwise
* Legal ops: ! ~ & ^ | +
* Max ops: 10
* Rating: 1
*/
方法一:
补码表示的最大值为:0x 7fff ffff,其用二进制表示就是0111 1111 .... 1111
我们发现,当0x 7fff ffff加1就变成了tmin,也就是1000 0000 .... 0000
那么,把tmin减1就可以得到这个补码表示的最大值了,由于不能用减号,我们可以加-1,而-1可以写成~0x1+1
int isTmax(int x) {
int ans=0x1<<31;
int max=ans+(~0x1+1);
return !(max-x);
}
方法二:
以四位为例,则最大值为x=0111,我们将x+1后再取反,又得到了x。
不信你看,x+1=1000,~(x+1)=0111,因此我们用异或操作来判断它是不是最大值->~(x+1)^x。
不过,这种方法有个特例。当x=-1时,也就是x=1111,x+1=0000(发生了溢出),~(x+1)=1111,
~(x+1)^x =1111,所以要加一个判断条件,判断它是不是-1
int isTmax(int x) {
return !(~(x+1)&x) && !!(x+1);
}
4.判断是否所有的奇数位的数字都为1
/*
* allOddBits - return 1 if all odd-numbered bits in word set to 1
* where bits are numbered from 0 (least significant) to 31 (most significant)
* Examples allOddBits(0xFFFFFFFD) = 0, allOddBits(0xAAAAAAAA) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 12
* Rating: 2
*/
构造所有奇数位为1的数——0x AAAA AAAA(也就是1010 1010 1010 .