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: 做一个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 10001010111Solution
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
阅读 2235·2021-11-24 11:15
阅读 3078·2021-11-24 10:46
阅读 1377·2021-11-24 09:39
阅读 3923·2021-08-18 10:21
阅读 1477·2019-08-30 15:53
阅读 1394·2019-08-30 11:19
阅读 3318·2019-08-29 18:42
阅读 2321·2019-08-29 16:58