码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Add Binary

时间:2015-05-17 21:48:42      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

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

Add Binary

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

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

 


 

长整型二进制加法。

 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 };

 

不让我调自带函数一行搞定,精度不够,机智的test case。

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

 

[LeetCode][JavaScript]Add Binary

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4510508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!