[LeetCode][JavaScript]Add Binary
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); }; */
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。