67. Add Binary
Add Binary
Given two binary strings a
and b
, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a
andb
consist only of'0'
or'1'
characters.- Each string does not contain leading zeros except for the zero itself.
Approach) Using Bigint
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function(a, b) {
const aBin = `0b${a}`
const bBin = `0b${b}`
const sum = BigInt(aBin) + BigInt(bBin)
return sum.toString(2)
};
Approach) Using Bigint - Single line
var addBinary = function(a, b) {
return (BigInt("0b"+a) + BigInt("0b"+b)).toString(2);
}
Approach) Brute Force
let addBinary = (a, b) => { // Truth Table // 1st + 2nd + carry = sum, new carry, decimal sum // 0 + 0 + 0 = 0, 0 (0) // 0 + 0 + 1 = 1, 0 (1) // 0 + 1 + 1 = 0, 1 (2) // 1 + 1 + 1 = 1, 1 (3) let carry = 0; let result = ''; let len1 = a.length - 1; let len2 = b.length - 1; for (; len1 >= 0 || len2 >= 0 || carry > 0; len1--, len2--) { let sum = (+a[len1] || 0) + (+b[len2] || 0) + carry; if (sum > 1) { sum = sum % 2; carry = 1; } else { carry = 0; } result = `${sum}${result}`; } return result; };
Conclusion
That’s all folks! In this post, we solved LeetCode problem 67. Add Binary
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment