forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0067-add-binary.c
24 lines (21 loc) · 780 Bytes
/
0067-add-binary.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
char*addBinary(constchar*a, constchar*b) {
intmaxLen=strlen(a) >strlen(b) ? strlen(a) : strlen(b);
char*res= (char*)malloc((maxLen+2) *sizeof(char));
memset(res, 0, (maxLen+2) *sizeof(char));
unsigned intcarry=0;
for(inti=0; i<maxLen; i++) {
unsigned intbitA=i<strlen(a) ? a[strlen(a) -i-1] -'0' : 0;
unsigned intbitB=i<strlen(b) ? b[strlen(b) -i-1] -'0' : 0;
unsigned inttotal=bitA+bitB+carry;
charsum='0'+total % 2;
carry=total / 2;
// Add to the beginning of the string
memmove(res+1, res, strlen(res));
res[0] =sum;
}
if(carry) {
memmove(res+1, res, strlen(res));
res[0] ='1';
}
returnres;
}