Add Binary
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Solution:
class Solution:
def addBinary(self, a: str, b: str) -> str:
x, y = int(a, 2), int(b, 2)
while y:
answer = x ^ y
carry = (x & y) << 1 # 左移相当于 当前值*2
x, y = answer, carry
return bin(x)[2:]
# bin(x)[2:]表示将二进制字符串中前两个字符去掉,返回剩余的字符串
人生便是艺术。