我必须想办法添加两个存储在数组中的二进制数,二进制数可以是任意大小;即:
Employee
这是我的头脑,但这是我到目前为止所做的:
Sample input and output:
101 + 11 = 1000
111 + 111 = 1110
1010 + 1010 = 10100
11101 + 1010 = 100111
11111 + 11111 = 111110
请随意撕开我,我真的遇到了麻烦,我认为我有逻辑,我只是无法弄清楚如何将其翻译成代码。
现在,如果我输入第一个例子,我得到:
输入a的大小 3 输入b的大小 2 输入3的内容 1 0 1 输入b 2的内容 1 1 -18174002763276720728465360000100
显然这里存在一个问题。有人可以帮忙吗?
答案 0 :(得分:1)
像这样调整你的代码:
void addition (int a[], int b[], int sizea, int sizeb, int result[]){
int maxSize = sizea > sizeb ? sizea : sizeb; // number of bits is maximum of siza and sizeb
int carry = 0;
for( int i = 0; i < maxSize; i++ )
{
int bitA = i < sizea && a[i] ? 1 : 0; // test if bit in array a is set
int bitB = i < sizeb && b[i] ? 1 : 0; // test if bit in array b is set
int sum = bitA + bitB + carry; // calculate sum of all bits
result[i] = sum == 1 || sum == 3 ? 1 : 0; // result bit is set if sum is equal 1 or 3
carry = sum > 1 ? 1 : 0; // carry bit is set if sum is eaul 2 or 3
}
result[ maxSize ] = carry; // highest bit of result is carry bit
for (int i = 0; i <= maxSize; i++){
cout << result[maxSize-i];
}
cout << endl;
}