0%

Javascript(leetcode#67) Add Binary

Difficult:Easy

題目

Given two binary strings a and b, return their sum as a binary string.

翻譯

給定兩個二進製字符串 a 和 b,將它們的和作為二進製字符串返回。

範例

Example 1

1
2
Input: a = "11", b = "1"
Output: "100"

Example 2

1
2
Input: a = "1010", b = "1011"
Output: "10101"

解題思路

1.從最後開始計算超過2進位

Solution

Code 1 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var addBinary = function (a, b) {

let len = Math.max(a.length - 1, b.length - 1);
let lens = 0;
let str = [];
let n = 0;
while (lens <= len || n == 1) {
let aval = parseInt(a[a.length - 1 - lens]) || 0;
let bval = parseInt(b[b.length - 1 - lens]) || 0;
let sum = aval + bval + n;
if (sum > 1) {
n = 1;
sum %= 2;
} else {
n = 0;
}
str.unshift(sum);
lens++;
}
return str.join("");
};