BB的面试题-只用&和| 如何reverse a bit string?# JobHunting - 待字闺中h*g2011-03-21 07:031 楼given 10001110want to get 01110001只能用 and/or这两种 bit operation
g*s2011-03-21 07:032 楼用& | 和 bit shift的方法有,只用& |的还真不知道unsigned __int32 reversing_bits(unsigned __int32 input){// complixity O(log [no.of.bits]) = O(1)// On 32 bit machines it takes 5 steps (logical)// Step 1// Mask bit positions 0, 2, 4... shift LEFT this masked number by one// Mask bit positions 1, 3, 5... shift RIGHT this masked number by oneinput = (input & 0x55555555) << 1 | (input & 0xAAAAAAAA) >> 1;// Step 2// Mask bit positions 01, 45, 89... shift LEFT this masked number by two// Mask bit positions 23, 67... shift RIGHT this masked number by twoinput = (input & 0x33333333) << 2 | (input & 0xCCCCCCCC) >> 2;// Step 3input = (input & 0x0F0F0F0F) << 4 | (input & 0xF0F0F0F0) >> 4;// Step 4input = (input & 0x00FF00FF) << 8 | (input & 0xFF00FF00) >> 8;// Sept 5input = (input & 0x0000FFFF) << 16 | (input & 0xFFFF0000) >> 16;return input;}
g*s2011-03-21 07:033 楼没空间开销约束的话好办啊。就一位一位的&,记录下每一位,再倒过来一位一位or即可。【在 h*****g 的大作中提到】: given 10001110: want to get 01110001: 只能用 and/or这两种 bit operation