https://leetcode.com/problems/add-binary/
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
计算过程类似Verilog的全加器。
char* addBinary(char* a, char* b) {int i;int l1, l2, l3, temp;l1 = strlen(a);l2 = strlen(b);l3 = l1 > l2 ? l1 + 2 : l2 + 2;temp = l3;char *result = (char *)malloc(l3 * sizeof(char));int t1, t2;int sum, cout = 0;cout = 0;l1--;l2--;l3--;result[l3] = '\0';while (l1 >= 0 || l2 >= 0) {t1 = l1 >= 0 ? a[l1] - '0' : 0;t2 = l2 >= 0 ? b[l2] - '0' : 0;sum = t1 ^ t2 ^ cout;cout = (t1 & t2) | (t1 & cout) | (t2 && cout);result[--l3] = sum + '0';l1--;l2--;}if (cout == 1)result[--l3] = '1';else {for(int i = 1; i < temp; i++) {result[i-1] = result[i]; // move left}}return result;
}