[LeetCode][JavaScript]Add Binary

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

https://leetcode.com/problems/add-binary/

 

 


 

 

长整型二进制加法。

模拟手工加法的过程,有进位。

 

 1 /**
 2  * @param {string} a
 3  * @param {string} b
 4  * @return {string}
 5  */
 6 var addBinary = function(a, b) {
 7     if(a.length < b.length){
 8         var tmp = a;
 9         a = b;
10         b = tmp;
11     }
12 
13     var res = "";
14     var carry = 0;
15     for(var i = 1; i <= a.length; i++){
16         var _a = parseInt(a[a.length - i]);
17         var _b = parseInt(b[b.length - i]) || 0;
18         var add = _a + _b + carry;
19         if(add === 3){
20             res = "1" + res;
21             carry = 1;
22         }else if(add === 2){
23             res = "0" + res;
24             carry = 1;
25         }else{
26             res = add + res;
27             carry = 0;
28         }
29     }
30 
31     if(carry === 1){
32         res = "1" + res;
33     }
34     return res;
35 };

 

并不能调自带函数一行搞定,精度不够。

/*
var addBinary = function(a, b) {
    return (parseInt(a, 2) + parseInt(b, 2)).toString(2);
};
*/

 

posted @ 2015-05-17 21:22  `Liok  阅读(638)  评论(0编辑  收藏  举报