[LeetCode][JavaScript]Add Binary

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.