Update Bits
题目:
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)
Given N=(10000000000)2, M=(10101)2, i=2, j=6
return N=(10001010100)2
分析:
这题目需要几个mask,但是如何形成mask需要注意,当j == 31和j != 31的时候要分开处理
背诵题,背过就是会,忘了就完蛋
解法:
class Solution {
public:
/**
*@param n, m: Two integer
*@param i, j: Two bit positions
*return: An integer
*/
int updateBits(int n, int m, int i, int j) {
// write your code here
int max = ~0;
if (j == 31) {
j = max;
} else {
j = (1 << (j + 1)) - 1;
}
int left = max - j;
int right = (1 << i) - 1;
int mask = left | right;
return (m << i) + (n & mask);
}
};