程序员面试金典-0501-插入

程序员面试金典-0501-插入

思路:
//1.Convert N and M to binary
//2.Set the bits i to j of N to 0
//3.Calculate the effective bit of M,that is, the first bit is 1 to the end.effe_bit_m->31
//4.Put the effective bits of M into N
//5.Convert binary to decimal

给定两个整型数字 N 与 M,以及表示比特位置的 i 与 j(i <= j,且从 0 位开始计算)。

编写一种方法,使 M 对应的二进制数字插入 N 对应的二进制数字的第 i ~ j 位区域,不足之处用 0 补齐。
题目保证从 i 位到 j 位足以容纳 M, 例如: M = 10011,则 i~j 区域至少可容纳 5 位。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insert-into-bits-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
int * con_int_to_bin(int num,int *data,int len){
    int temp = 1;
    int d = num;
    int i = 0;
    for(i=len-1;i>-1;i--){
        int t = (d&temp);
        data[i]=t;
        d = d>>1;
    }
    return data;
}
int con_bin_to_int(int *data,int len){
    int ret = 0;
    int i  =0;
    for(i=0;i<len;i++){
        ret = ret<<1;   //only ret<<1 like i+1 ,not modify i
        ret = ret+data[i];
    }
    return ret;
}
//1.Convert N and M to binary
//2.Set the bits i to j of N to 0
//3.Calculate the effective bit of M,that is, the first bit is 1 to the end.effe_bit_m->31
//4.Put the effective bits of M into N
//5.Convert binary to decimal
int insertBits(int N, int M, int i, int j){
    //1.Convert N and M to binary
    int ret = 0;
    int len = 32;
    int * b1 = malloc(sizeof(int)*32);
    int * b2 = malloc(sizeof(int)*32);
    b1 = con_int_to_bin(N,b1,len);
    b2 = con_int_to_bin(M,b2,len);

    //2.Set the bits i to j of N to 0
    int p1 = len-i-1;
    int p2 = len-j-1;
    int pi = 0;
    for(pi=p1;pi>=p2;pi--)
        b1[pi]=0;
    //3.Calculate the effective bit of M,that is, the first bit is 1 to the end.effe_bit_m->31
    if(M==0){
        ret = con_bin_to_int(b1,len);
        return ret;
    }
    int effe_bit_M=0;
    for(pi=0;pi<len;pi++){
        if(b2[pi]==1){
            effe_bit_M=pi;
            break;
        }
    }
    //4.Put the effective bits of M into N
    for(pi=len-1;pi>=effe_bit_M;pi--){
        b1[p1]=b2[pi];
        p1--;
    }

    //5.Convert binary to decimal
    ret = con_bin_to_int(b1,len);
    free(b1);
    free(b2);
    return ret;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值