程序员面试金典-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;
}