Loading

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:]表示将二进制字符串中前两个字符去掉,返回剩余的字符串
posted @ 2023-06-15 11:07  Artwalker  阅读(4)  评论(0编辑  收藏  举报
Live2D