stringaddBinary(string a, string b){ bool c = false; int lena = a.length(); int lenb = b.length(); string res=""; int i = lena - 1; int j = lenb - 1; while (i >= 0 && j >= 0) {
if (c)//有进位 { if (a[i] == '1') { if (b[j] == '1') res = "1"+ res; else res = "0" + res; } else { if (b[j] == '0') { res = "1" + res; c = false; } else res = "0" + res; } } else { if (a[i] == '1') if (b[j] == '1') { res = "0" + res; c = true; } else res = "1" + res; else res = b[j] + res; } i--; j--; } while (i >= 0) { if (c) if (a[i] == '1') res = "0" + res; else { res = "1" + res; c = false; } else res = a[i] + res; i--; } while (j >= 0) { if (c) { if (b[j] == '1') res = "0" + res; else { res = "1" + res; c = false; } } else res = b[j] + res; j--; } if (c)return'1' + res; return res; }
classSolution: defaddBinary(self, a, b) -> str: x, y = int(a, 2), int(b, 2) while y: x, y = x ^ y, (x & y) << 1 return bin(x)[2:] 链接:https://leetcode-cn.com/problems/add-binary/solution/er-jin-zhi-qiu-he-by-leetcode/