[Lintcode]179. Update Bits

本文介绍了一种使用位操作在给定的32位数N中,将从i到j位置的所有位设置为另一个32位数M的方法。通过具体的例子和Python代码实现,展示了如何在不改变N的其他位的情况下,将M嵌入到N的特定区间内。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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做位运算好难哦

转载于:https://www.cnblogs.com/siriusli/p/10359887.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值