您的位置:首页 > 运维架构

#179 Update Bits

2016-08-07 11:47 120 查看
题目描述:

Given two 32-bit numbers, N and M, and two bit positions, iand 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)


 Notice


In the function, the numbers N and M will given in decimal, you should also return a decimal number.

Have you met this question in a real interview? 

Yes

Clarification

You can assume that the bits j through i have enough space to fit all of M. That is, if M=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.

Example

Given 
N=(10000000000)2
M=(10101)2
i=2
j=6

return 
N=(10001010100)2


Challenge 

Minimum number of operations?

解题思路:

这题的思路应该很多。我想到的一种比较容易想清楚的解法是:先把N中i到j位的bit清零(这个操作可以用一个mask做到),再加上M*2^i即可。这题比较容易出错的地方是要考虑到m或n < 0的情况,这种情况下不能直接做bit operation,应该先用long long的type将m或n存起来,如果<0则加上2^32,改成正数再做上述操作。

Mycode(AC = 22ms):

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
long long long_n = n, long_m = m;
if (long_n < 0) {
long_n += pow(2, 32);
}
if (long_m < 0) {
long_m += pow(2, 32);
}

// mask = 11111...111
long long mask = pow(2, 32) - 1;
int idx = i; // 2
while (idx <= j) {
mask -= pow(2, idx); // mask - 2^2 - 2^3... - 2^6
idx++;
}

long long ans = mask & long_n; // ans = 10000000000
ans += long_m * pow(2, i); // ans + 10101 << 2

return (int)(ans > (long long)pow(2, 32) ? ans - (long long)pow(2, 32): ans);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode bit operation