(原问题见算法导论第三版2.1-4)
问题:考虑把两个n位二进制数加起来的问题。这两个整数分别存储在两个n元数组A和B中。这两个整数的和应按二进制形式存储在一个(n + 1)元数组C中。
解答:
代码如下。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void binary_add(int *, int *, int *, int);
int main(int argc, char const *argv[])
{
/* code */
if (argc < 3) {
fprintf(stderr, "please input enough binary number\n");
return -1;
}
const char* num1 = argv[1];
const char* num2 = argv[2];
int n1 = strlen(num1);
int n2 = strlen(num2);
int n = (n1 > n2) ? n1 : n2;
int * left = calloc(n1, sizeof(int));
int * right = calloc(n2, sizeof(int));
int * result = calloc(n + 1, sizeof(int));
for (int i = 0; i < n1; ++i) {
if (num1[i] == '1') {
left[n1 - i - 1] = 1;
} else if (num1[i] == '0') {
left[n1 - i - 1] = 0;
} else {
fprintf(stderr, "error input left number, please input binary number\n");
return -1;
}
}
for (int i = 0; i < n2; ++i) {
if (num2[i] == '1') {
right[n2 - i - 1] = 1;
} else if (num2[i] == '0') {
right[n2 - i - 1] = 0;
} else {
fprintf(stderr, "error input right number, please input binary number\n");
return -1;
}
}
for (int i = 0; i < n + 1; ++i)
{
if (i < n + 1 - n1) {
printf(" ");
} else {
printf("%d", left[n1 - (i - n - 1 + n1) - 1]);
}
}
printf("\n");
for (int i = 0; i < n + 1; ++i)
{
if (i < n + 1 - n2) {
printf(" ");
} else {
printf("%d", right[n2 - (i - n - 1 + n2) - 1]);
}
}
printf("\n");
binary_add(left, right, result, n);
for (int i = 0; i < n + 1; ++i)
{
printf("%d", result[n - i]);
}
printf("\n");
return 0;
}
void binary_add(int *left, int *right, int *result, int n) {
int c = 0;
int temp;
for (int i = 0; i < n; i++) {
temp = left[i] + right[i] + c;
result[i] = temp % 2;
c = temp / 2;
}
if (c != 0) {
result[n] = c;
}
}