资讯专栏INFORMATION COLUMN

[LintCode/CC] Update Bits [Merge Bits]

KnewOne / 2854人阅读

Problem

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)

Notice

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

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?

Note

我们把n的第i位到第j位都变成0,然后加上左移i位的m,不就是所求了吗?
所以把n的第i位到第j位置零,可以这样操作:
j < 31: 做一个mask = ~(1 << j+1) - (1 << i),让mask成为一个第i位到第j位都是0,而高于第j位和低于第i位都是1的这样一个数。然后,和n相与,保证了n在j以上高位,i以下低位的数字不变,且第i到j位为0.
j >= 31: 做一个mask = 1 << i - 1,即长度为i,每一位都为1的数字。这样做掩模的原因是,因为j超过了n的最高位,意味着从第i位向上的所有位都会被m替换,所以只要用这个掩模和n相与,保留n的最后i位就可以了。
最后与左移i位的数m相加,返回结果。

N = (10000000011)2, M = (10101)2, i = 2, j = 6,
mask = ~(1000000 - 100) = ~111100 = 111...111000011 (32 digits),
m << 2 = 1010100, 
mask & n = 11111000011 & 10000000011 = 10000000011
so return 10001010111
Solution
class Solution {
    public int updateBits(int n, int m, int i, int j) {
        int mask = 0;
        if (j < 31) mask = ~((1<           
               
                                           
                       
                 

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65671.html

相关文章

发表评论

0条评论

最新活动
阅读需要支付1元查看
<