国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode/CC] Update Bits [Merge Bits]

KnewOne / 3100人閱讀

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<           
               
                                           
                       
                 

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/65671.html

相關文章

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<