67. Add Binary
难度: Easy
刷题内容
原题连接
内容描述
1 2 3 4 5 6 7 8 9 10 11 12
| Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1" Output: "100" Example 2:
Input: a = "1010", b = "1011" Output: "10101"
|
解题方案
思路 1
**- 时间复杂度: O(N)**- 空间复杂度: O(N)**
- 对于每一位数进行加法,如有进位单独计算
- 注意需使用字符串进行存储,整型无法计算大型数据
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
var addBinary = function(a, b) { var tempA = a.split(''); var tempB = b.split(''); var result =[]; var aLen=tempA.length,bLen=tempB.length; var carry = 0; while(aLen>0||bLen>0){ var charA=0,charB=0; if(aLen>0) charA = tempA[--aLen]-0; if(bLen>0) charB = tempB[--bLen]-0; var temp = charA + charB + carry; carry = temp>1?1:0; result.unshift(temp%2); } if(carry===1) result.unshift(1); return result.toString().replace(/,/g,''); };
|