题目:
You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).
EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6
Output: N = 10001010100
实现:
unsigned int SetBits(unsigned int N, unsigned int M, unsigned int i, unsigned int j)
{
return (((N >> j) << j) | (M << i) | (N % (2 << i)));
}
说明:其中(N >> j) << j用于获取N中j左边的数据;M << i将M偏移i的位移,以便放到N中从i开始的位置;N % (2 << i)用于获取N中i右边的数据。