合并二进制字符串并在 C 中插入位

Merge binary Strings and Insert bits in C

函数 insertBits

X 和 Y 是两个整数值。

函数 insertBits 必须在 X 的最后一个设置位之后插入 Y 的所有位。 那么函数必须 return 一个表示 X 的修正值的整数。

Input:

10 14

Output:

188

Explanation:

10 -> 1010
14 -> 1110

After inserting 1110 after the last set bit in 1010 the binary representation of X becomes 10111100.
The decimal equivalent of 10111100 is 188.


Input:

152 9

Output:

2504

Explanation:

152 -> 10011000
9 -> 1001

After inserting 1001 after the last set bit in 10011000, the binary representation of X becomes 100111001000.
The decimal equivalent of 100111001000 is 2504.

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

long bin(long n)
{
    long d,r,binary=0;
    d=n;
    int temp=1;
    while(n!=0)
    {
        r=n%2;
        n=n/2;
        binary=binary+r*temp;
        temp=temp*10;
    }
    return binary;
}


int insertBits(int X, int Y)
{
    bin(X);
    bin(Y);

     ///
    
}

int main()

{

    int X, Y;
    scanf("%d %d", &X, &Y); 
    printf("%d", insertBits(X, Y)); 
    return 0;

}

我把十进制转换成了二进制。但是我不知道如何在X中插入这些位。

不要使用十进制算术。二进制更简单明了:

uint32_t bitshift(uint32_t x, uint32_t y)
{
    // put y in the result
    uint32_t result = y;
    // shift by the trailing 0s in x
    while (x && !(x & 1)) {
        x /= 2;
        result *= 2;
    }
    // find the shift for x, which is larger than result
    uint32_t shift = 1;
    while (shift && shift <= result) shift *= 2;
    // put x in the right place
    result |= x * shift;
    return result;
}

int main()
{
    printf("10 14 = %5u\n",bitshift(10,14));
    printf("152 9 = %5u\n",bitshift(152,9));
    // Test some corner cases
    printf("152 0 = %5u\n",bitshift(152,0));
    printf("0 152 = %5u\n",bitshift(0,152));
    printf("4 4   = %5u\n",bitshift(4,4));
    printf("1 0xffffffff = %5u\n",bitshift(1,0xffffffffU));

}

输出:

10 14 =   188
152 9 =  2504
152 0 =    19
0 152 =   152
4 4   =    48
1 0xffffffff = 4294967295

您应该使用 unsigned int 参数,计算 X 中尾随零的数量和 Y 中的位数,结果很容易通过移位操作获得:

unsigned int insertBits(unsigned int X, unsigned int Y) {
    int n1, n2;
    unsigned int temp;
    if (X == 0)
        return Y;
    if (Y == 0)
        return X;
    // compute the number of trailing zeroes in X
    for (n1 = 0, temp = X; (temp & 1) == 0; n1++, temp >>= 1)
         continue;
    // compute the number of bits in Y
    for (n2 = 0, temp = Y; temp != 0; n2++, temp >>= 1)
         continue;
    return ((X >> n1 << n2) | Y) << n1;
}