首页 > 代码库 > Careercup | Chapter 5

Careercup | Chapter 5

5.1 You are given two 32-bit numbers, N andM, and two bit positions, i and j. Write a method to insert M into Nsuch that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all ofM. That is, ifM= 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j-3 and i=2, because M could not fully fit between bit 3 and bit 2.

update某一位的时候,记得要把该位清零先。

Method 1: mask = ~((1<<(i-j+1)-1)<<i)

Method 2:mask=(~0<<(j+1)) | ((1<<i) - 1)

5.2 Given a real number between 0 and 7 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR."

小数的表示啊。用除法得到的是reverse的串。用乘法可以得到正串。

5.3 Given a positive integer, print the next smallest and the next largest number that have the same number of 7 bits in their binary representation.

用位操作方法很直观,用算术方法比较巧妙一些。arithmetically。 

getNext: n + (1 << c0) + (1 << (c1-1)) - 1;

getPrev: n - (1 << c1) - (1 << (c0-1)) + 1; 

 5.4 Explain what the following code does: ((n & (n-1)) == 0).

check一下n是不是2的k次方。

也可以用来检验二进制中1的个数。

5.5 Write a function to determine the number of bits required to convert integer A to integer B.

就是用n&(n-1)来计算。这个操作每次可以把least significant bit为1的给清零。

5.6 Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit! are swapped, bit 2 and bit 3 are swapped, and so on)

巧妙。移偶数位,移奇数位。

5.7