Michael Lo

Command Palette

Search for a command to run...

Blog
PreviousNext

Add Binary

--

Add two binary strings and return their sum in binary format

Add two binary strings and return the sum as a binary string

問題描述

給你兩個二進制字符串 ab,以二進制字符串的形式返回它們的和。

範例

輸入: a = "11", b = "1"
輸出: "100"

輸入: a = "1010", b = "1011"
輸出: "10101"

限制條件

  • 1 <= a.length, b.length <= 10⁴
  • ab 僅由字符 '0''1' 組成
  • 字符串如果不是 "0",就不含前導零

解題思路

### 模擬手工加法 從最低位開始逐位相加,處理進位
### 處理不同長度 較短的字符串補 0 處理
### 進位處理 每位運算結果可能產生進位,需要傳遞到下一位

解決方案

typescript
export function addBinary(a: string, b: string): string {
  let carry = 0;
  let result = '';
  let i = a.length - 1;
  let j = b.length - 1;
 
while (i >= 0 || j >= 0 || carry > 0) {
const digitA = i >= 0 ? Number.parseInt(a[i]) : 0;
const digitB = j >= 0 ? Number.parseInt(b[j]) : 0;
 
    const sum = digitA + digitB + carry;
    result = (sum % 2) + result;
    carry = Math.floor(sum / 2);
 
    i--;
    j--;
 
}
 
return result;
}
 
export function addBinaryBigInt(a: string, b: string): string {
  const aBin = `0b${a}`;
  const bBin = `0b${b}`;
 
const sum = BigInt(aBin) + BigInt(bBin);
return sum.toString(2);
}
 

相關題目