We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
2 parents b3d1baa + e75b429 commit 6029314Copy full SHA for 6029314
1 file changed
c/0067-add-binary.c
@@ -0,0 +1,24 @@
1
+char *addBinary(const char *a, const char *b) {
2
+ int maxLen = strlen(a) > strlen(b) ? strlen(a) : strlen(b);
3
+ char *res = (char *)malloc((maxLen + 2) * sizeof(char));
4
+ memset(res, 0, (maxLen + 2) * sizeof(char));
5
+ unsigned int carry = 0;
6
+
7
+ for(int i = 0; i < maxLen; i++) {
8
+ unsigned int bitA = i < strlen(a) ? a[strlen(a) - i - 1] - '0' : 0;
9
+ unsigned int bitB = i < strlen(b) ? b[strlen(b) - i - 1] - '0' : 0;
10
11
+ unsigned int total = bitA + bitB + carry;
12
+ char sum = '0' + total % 2;
13
+ carry = total / 2;
14
15
+ // Add to the beginning of the string
16
+ memmove(res + 1, res, strlen(res));
17
+ res[0] = sum;
18
+ }
19
+ if(carry) {
20
21
+ res[0] = '1';
22
23
+ return res;
24
+}
0 commit comments