The problem appears in [url]http://acm.hnu.cn:8080/online/?action=problem&type=show&id=10475[\url]
Just very simple method, first I reverse the binary number. Then I fill the zero in the remaining space. For example, a = 1001011111, b = 11110001.
Code:
1) reverse
1001011111 ---> 1111101001
11110001 ---> 10001111
2) fill zero
10001111 ---> 1000111100
3) adding two binary number
1111101001
1000111100
--------------
1101010000
Here is my code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXDIGIT 100
char a[MAXDIGIT], b[MAXDIGIT];
int n;
void reverse(char *x)
{
char tmp;
int i, len = strlen(x);
for (i = 0; i < len/2; i++) {
tmp = x[i];
x[i] = x[len-i-1];
x[len-i-1] = tmp;
}
}
void fillZero(char *a, char *b)
{
int i;
if (strlen(a) > strlen(b)) {
for (i = strlen(b); i < strlen(a); i++)
b[i] = '0';
i++;
b[i] = '\0';
} else if (strlen(a) < strlen(b)) {
for (i = strlen(a); i < strlen(b); i++)
a[i] = '0';
i++;
a[i] = '\0';
}
}
int chr2int(char x)
{ return (int)x-'0'; }
void base2Plus()
{
int i, tmp, len;
int result[MAXDIGIT];
reverse(a);
reverse(b);
fillZero(a, b);
tmp = 0;
for (i = 0, len = 0; i < strlen(a); i++, len++) {
tmp += chr2int(a[i])+chr2int(b[i]);
result[len] = tmp%2;
tmp = (tmp <= 1) ? 0 : 1;
}
if (tmp == 1) {
result[len] = tmp%2;
len++;
}
for (i = len-1; i >= 0; i--)
printf("%d", result[i]);
printf("\n");
}
int main()
{
int i;
scanf("%d", &n);
for (i = 1; i <= n; i++) {
scanf("%s %s", a, b);
printf("%d ", i);
base2Plus();
}
return 0;
}
But I cannot pass the task of the mentioned problem. What are the bugs here?