我接受了一次采访,被要求在第I位加上2个带-2索引的整数,即-2幂I我给出了下面的答案,但被告知这个答案不是有效的和错误的。我不同意有效的评论,但可能同意不正确。
我加的方法是,如果2位的和大于等于2,则取-1的进位,因为相邻的位有相反的符号。如果加2位是-1,我就把它变成1,取1的进位到相邻的位。
有人看到代码有问题吗?
struct Results solution ( int A[], int M, int B[], int N ) {
struct Results result;
int min =M;
int max = M;
int i=0;
int sum;
int carry = 0;
if(N<M)min = N;
if(N>M)max = N;
result.C = (int*) malloc(sizeof(int) * max);
for(i=0;i<min;i++){
sum = A[i] + B[i] + carry;
if(sum >= 2 ){
if(carry == 0 )
carry = -1;
else
carry = -carry;
sum = sum-2;
}
else if(sum == -1){
sum = 1;
carry = 1;
}
else{
carry=0;
}
result.C[i] = sum;
}
if( M > N){
result.L = M;
for(i=N;i<M;i++){
sum = A[i]+carry;
if(sum >= 2 ){
if(carry == 0 ) carry = -1;
else carry = 1;
sum = sum-2;
}
else if(sum == -1){
sum = 1;
carry = - carry;
}
else{carry=0;}
result.C[i] = sum;
}
}
if( N > M){
result.L = N;
for(i=M;i<N;i++){
sum = B[i]+carry;
if(sum >= 2 ){
if(carry == 0 ) carry = -1;
else carry = -carry;
sum = sum-2;
}
else if(sum == -1){
sum = 1;
carry = 1;
}
else{carry=0;}
result.C[i] = sum;
}
}
return result;
}
int main(int argc, char* argv[])
{
int A[] = {0,1,1,0,0,1,0,1,1,1,0,1,0,1,1};
int B[] = {0,0,1,0,0,1,1,1,1,1,0,1};
solution (A,15,B ,12 );
}
最佳答案
问题1
如果2位的和大于等于2,则使用-1的进位,但在其中一种情况下,您拥有代码:
if(sum >= 2 ){
if(carry == 0 ) carry = -1;
else carry = 1;
sum = sum-2;
}
这将把进位设置为1,而不是-1。
您还可以争辩说,这段代码可以更有效地编写为:
if(sum >= 2 ){
carry = -1;
sum = sum-2;
}
问题2
如果我们添加{1}和{1},会发生什么?
您将返回长度1和结果{0},但答案应该是{0,1,1}(1+1=-2+4)
换句话说,您可能需要返回比输入最大值更多的位。