67.Add Binary

tags: Easy,Math,String,Bit Manipulation

67. 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"

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

解答

Python

class Solution: def addBinary(self, a: str, b: str) -> str: x, y = int(a, 2), int(b, 2) while y: x, y = x ^ y, (x & y) << 1 return bin(x)[2:]

Ron ChenFeb 14, 2023

Javascript

function addBinary(a, b) { return (BigInt(`0b${a}`) + BigInt(`0b${b}`)).toString(2); }

學到js新用法,但這樣寫好像不是題目想要的XDD
MarsgoatFeb 14, 2023

Reference

回到題目列表