67. 二进制求和
题目描述: 给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
和66题类似,利用carry变量记录加1位
//C //这里需要注意字符串数组默认最后一位应该为\0,分配内存的时候应该加1并手动添加结束符 #define max(a, b) ((a) > (b) ? (a) : (b)) char * addBinary(char * a, char * b){ int lena = strlen(a), lenb = strlen(b), carry = 0, tmp = 0; int len = max(lena, lenb), i = lena - 1, j = lenb - 1; int idx = len - 1; char *p = (char *)malloc(sizeof(char)* (len + 1)); p[len] = '\0'; while (i >= 0 || j >= 0){ if (i >= 0 && j >= 0) tmp = (a[i] - '0') + (b[j] - '0') + carry; else if (i >= 0) tmp = (a[i] - '0') + carry; else tmp = (b[j] - '0') + carry; if (tmp == 2) { p[idx--] = '0'; carry = 1; } else if (tmp == 3){ p[idx--] = '1'; carry = 1; } else{ carry = 0; p[idx--] = tmp + '0'; } i--; j--; } if (carry == 1){ char *q = (char *)malloc(sizeof(char)* (len + 2)); q[0] = '1'; for (i = 0; i < len + 1; i++) q[i + 1] = p[i]; return q; } else{ return p; } }
另一种比较优美的写法。
//C char * addBinary(char * a, char * b){ int len1 = strlen(a),len2 = strlen(b),carry = 0,k = 0; int i,j; char *c = (char *)malloc(sizeof(char)*(len1 + len2)); //核心代码,从右往左进行运算 for(i = len1 - 1,j = len2 - 1;i >= 0 || j >= 0 || carry;--i,--j){ //很可能有a,b数组长度不等的时候,所以会有i,j小于0的情况,这时直接把该位置为0即可 int x = i < 0 ? 0 : a[i] - '0'; int y = j < 0 ? 0 : b[j] - '0'; int sum = (x + y + carry) % 2; //存入数组中的值 carry = (x + y + carry) / 2; //进位 c[k++] = sum + '0'; } c[k] = '\0'; //结束字符 //翻转字符串 for(i = 0,j = k - 1;i < j;i++,j--){ char cc = c[i]; c[i] = c[j]; c[j] = cc; } return c; } //JS var addBinary = function(a, b) { let res = "", carry = 0, tmp = 0, lena = a.length, lenb = b.length; for(var i = lena - 1, j = lenb - 1; i >= 0 || j >= 0 || carry; i--, j--){ let x = i >= 0 ? Number(a[i]) : 0, y = j >= 0 ? Number(b[j]) : 0; tmp = carry + x + y; if(tmp >= 2){ carry = 1; res = tmp % 2 + res; } else{ carry = 0; res = tmp + res; } } return res; };
JS中的BigInt数据类型
//JS var addBinary = function(a, b) { return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2); //0b是二进制前缀 }