成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

[LintCode/CC] Update Bits [Merge Bits]

KnewOne / 3126人閱讀

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: 做一個(gè)mask = ~(1 << j+1) - (1 << i),讓mask成為一個(gè)第i位到第j位都是0,而高于第j位和低于第i位都是1的這樣一個(gè)數(shù)。然后,和n相與,保證了n在j以上高位,i以下低位的數(shù)字不變,且第i到j(luò)位為0.
j >= 31: 做一個(gè)mask = 1 << i - 1,即長(zhǎng)度為i,每一位都為1的數(shù)字。這樣做掩模的原因是,因?yàn)閖超過(guò)了n的最高位,意味著從第i位向上的所有位都會(huì)被m替換,所以只要用這個(gè)掩模和n相與,保留n的最后i位就可以了。
最后與左移i位的數(shù)m相加,返回結(jié)果。

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<           
               
                                           
                       
                 

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/65671.html

相關(guān)文章

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<