原為某軟件公司試題,大意如下:對於給定的有符號32位整數,寫一個函數,當該數為正數時返回1,為負數時返回-1,為零時返回零,要求不能使用任何的條件判斷分支跳轉語句。在這裡,稍微擴展了一下,給出了對應無符號32位整數的情形。解決思路是符號位和值分開處理,對於有符號32位整數,符號位右移31位即得a,若為非負數則a=0x00000000,否則a=0xFFFFFFFF;然後將值部分各位的值(0或1)不斷縮小合並到一位中去得到b,這是針對0和正數的情況處理,再將a和b位或即可。C++代碼描述如下
1//若val為0則返回0, val為負數則返回-1, 為正數返回1
2int32_t check32(int32_t val)
3{
4 int32_t a = val >> 31;
5 int32_t b = (val & 0x0000FFFF) | ((val >> 16)&0x0000FFFF);
6 b = (b & 0x000000FF) | ((b >> 8)&0x000000FF);
7 b = (b & 0x0000000F) | ((b >> 4)&0x0000000F);
8 b = (b & 0x00000003) | ((b >> 2)&0x00000003);
9 b = (b & 0x00000001) | ((b >> 1)&0x00000001);
10 return a|b;
11}
12
13//若val為0則返回0, 否則返回1
14uint32_t check32(uint32_t val)
15{
16 uint32_t a = (val & 0x0000FFFF) | ((val >> 16)&0x0000FFFF);
17 a = (a & 0x000000FF) | ((a >> 8)&0x000000FF);
18 a = (a & 0x0000000F) | ((a >> 4)&0x0000000F);
19 a = (a & 0x00000003) | ((a >> 2)&0x00000003);
20 a = (a & 0x00000001) | ((a >> 1)&0x00000001);
21 return a;
22}
若哪位有更好的解法,還望多多分享