首页 > 代码库 > Add Binary

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".


#include<stdio.h>
#include<string.h>

char* addBinary(char a[], char b[]) {
    int na=strlen(a);
    int nb=strlen(b);
    int i,j,flag=0,k;
    int t1,t2,t3;
    int n=(na>nb)?na:nb;
    char c[100]="0";
    for(i=na-1,j=nb-1,k=n-1;k>=0;i--,j--,k--){
        if(i<0) t1=0;
        else t1=a[i]-48;
        if(j<0) t2=0;
        else t2=b[j]-48;
        t3=t1+t2+flag;
        if(t3>1) {
            t3=t3%2;
            flag=1;
        }
        else flag=0;
        c[k]=t3+'0';
    }        
    if(flag){
        c[n+1]='\0';
        for(k=n;k>0;k--) c[k]=c[k-1];
        c[k]='1';
    }
    else c[n]='\0';
    return c;
}

void main(){
    char a[]="110";
    char b[]="10";
    char *c=addBinary(a,b);
    int i;
}


Add Binary