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)
NoticeIn the function, the numbers N and M will given in decimal, you should also return a decimal number.
ClarificationYou 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.
ExampleGiven N=(10000000000)2, M=(10101)2, i=2, j=6
return N=(10001010100)2
ChallengeMinimum 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 10001010111Solution
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
閱讀 2267·2021-11-24 11:15
閱讀 3125·2021-11-24 10:46
閱讀 1427·2021-11-24 09:39
閱讀 3950·2021-08-18 10:21
閱讀 1501·2019-08-30 15:53
閱讀 1420·2019-08-30 11:19
閱讀 3354·2019-08-29 18:42
閱讀 2359·2019-08-29 16:58