[Lintcode]179. Update Bits

179. Update Bits

  • 本题难度: Medium
  • Topic: Bit Manipulation

Description

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 start from i to j)

Example
Given N=(10000000000)2, M=(10101)2, i=2, j=6

return N=(10001010100)2

Challenge
Minimum number of operations?

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.

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

别人的代码

class Solution:
    """
    @param n: An integer
    @param m: An integer
    @param i: A bit position
    @param j: A bit position
    @return: An integer
    """
    def updateBits(self, n, m, i, j):
        # write your code here
        tmp = ((~((((-1) << (31 - j) & 0xFFFFFFFF) >> (31 - j + i)) << i)) & 0xFFFFFFFF) & n | ((m << i) & 0xFFFFFFFF)
        
        if tmp & (1 << 31):
            return tmp ^ ~(0xFFFFFFFF)
        return tmp

思路

实在不会,python做位运算好难哦

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10359887.html