返回介绍

lcci / 05.01.Insert Into Bits / README_EN

发布于 2024-06-17 01:04:43 字数 2530 浏览 0 评论 0 收藏 0

05.01. Insert Into Bits

中文文档

Description

You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. 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.

Example1:


 Input: N = 10000000000, M = 10011, i = 2, j = 6

 Output: N = 10001001100

Example2:


 Input: N = 0, M = 11111, i = 0, j = 4

 Output: N = 11111

Solutions

Solution 1: Bit Manipulation

First, we clear the bits from the $i$-th to the $j$-th in $N$, then we left shift $M$ by $i$ bits, and finally perform a bitwise OR operation on $M$ and $N$.

The time complexity is $O(\log n)$, where $n$ is the size of $N$. The space complexity is $O(1)$.

class Solution:
  def insertBits(self, N: int, M: int, i: int, j: int) -> int:
    for k in range(i, j + 1):
      N &= ~(1 << k)
    return N | M << i
class Solution {
  public int insertBits(int N, int M, int i, int j) {
    for (int k = i; k <= j; ++k) {
      N &= ~(1 << k);
    }
    return N | M << i;
  }
}
class Solution {
public:
  int insertBits(int N, int M, int i, int j) {
    for (int k = i; k <= j; ++k) {
      N &= ~(1 << k);
    }
    return N | M << i;
  }
};
func insertBits(N int, M int, i int, j int) int {
  for k := i; k <= j; k++ {
    N &= ^(1 << k)
  }
  return N | M<<i
}
function insertBits(N: number, M: number, i: number, j: number): number {
  for (let k = i; k <= j; ++k) {
    N &= ~(1 << k);
  }
  return N | (M << i);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文