|
|
#2
兔先生2019-12-08 18:44
#include<stdio.h>
#include<stdlib.h> #include<string.h> char* addBinary(char* a, char* b) { int i, k, j, len; int c; c = 0; j = strlen(a); k = strlen(b); len = j > k ? j : k; char* res = (char*)malloc(sizeof(char) * (len + 2)); res[len + 1] = '\0'; i = len - 1; while (i >= 0) { if (j - 1 >= 0 && k - 1 >= 0) { if (a[j - 1] - '0' + b[k - 1] - '0' + c == 2) { res[i] = '0'; c = 1; } else { res[i] = a[j - 1] - '0' + b[k - 1] - '0' + c; c = 0; } } if (j - 1 < 0) { if (b[k - 1] - '0' + c == 2) { res[i] = '0'; c = 1; } else { res[i] = b[k - 1] - '0' + c; c = 0; } } if (k - 1 < 0) { if (a[j - 1] - '0' + c == 2) { res[i] = '0'; c = 1; } else { res[i] = a[j - 1] - '0' + c; c = 0; } } i--, j--, k--; } if (c > 0) res[0] = '1'; else (*res)++; return res; } int main() { char a[10] = "110"; char b[10] = "1001"; char* res; int i = 0; printf("%s",addBinary(a, b)); } 完整版代码 |
程序代码:char * addBinary(char * a, char * b){
int i,k,j,len;
int c;
c=0;
j=strlen(a);
k=strlen(b);
len=j>k?j:k;
char *res=(char *)malloc(sizeof(char)*(len+2));
res[len+1]='\0';
i=len-1;
while(i>=0)
{
if(j-1>=0&&k-1>=0){
if(a[j-1]-'0'+b[k-1]-'0'+c==2)
{
res[i]='0';
c=1;
}else
{
res[i]=a[j-1]-'0'+b[k-1]-'0'+c;
c=0;
}}
if(j-1<0)
{
if(b[k-1]-'0'+c==2)
{
res[i]='0';
c=1;
}else{
res[i]=b[k-1]-'0'+c;
c=0;
}
}
if(k-1<0)
{
if(a[j-1]-'0'+c==2)
{
res[i]='0';
c=1;
}
else{
res[i]=a[j-1]-'0'+c;
c=0;
}
}
i--,j--,k--;
}
if(c>0)
res[0]='1';
else
*res++;
return res;
}
int i,k,j,len;
int c;
c=0;
j=strlen(a);
k=strlen(b);
len=j>k?j:k;
char *res=(char *)malloc(sizeof(char)*(len+2));
res[len+1]='\0';
i=len-1;
while(i>=0)
{
if(j-1>=0&&k-1>=0){
if(a[j-1]-'0'+b[k-1]-'0'+c==2)
{
res[i]='0';
c=1;
}else
{
res[i]=a[j-1]-'0'+b[k-1]-'0'+c;
c=0;
}}
if(j-1<0)
{
if(b[k-1]-'0'+c==2)
{
res[i]='0';
c=1;
}else{
res[i]=b[k-1]-'0'+c;
c=0;
}
}
if(k-1<0)
{
if(a[j-1]-'0'+c==2)
{
res[i]='0';
c=1;
}
else{
res[i]=a[j-1]-'0'+c;
c=0;
}
}
i--,j--,k--;
}
if(c>0)
res[0]='1';
else
*res++;
return res;
}
大佬要是有时间顺便解决一下为什么输出会有"10�"这个问号
[此贴子已经被作者于2019-12-8 17:12编辑过]