How to solve the problem of binary summation in leetcode
Editor to share with you how to solve the problem of binary summation in leetcode, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
Topic link
Https://leetcode-cn.com/problems/add-binary/
Topic description
Given two binary strings, return their sum (in binary).
The input is a non-empty string and contains only the numbers 1 and 0.
Example 1:
Enter: a = "11", b = "1"
Output: "100"
Example 2:
Enter: a = "1010", b = "1011"
Output: "10101"
The idea of solving the problem
Tags: strin
The overall idea is to make up the shorter strings with 0, so that the length of the two strings is the same, and then traverse the end to get the final result.
The general idea of the solution to this question is the same as above, but due to string operation, it is uncertain whether the final result will have one more carry, so there will be two ways to deal with it.
The first is to concatenate the string directly during the calculation, resulting in a reverse character, which needs to be flipped at last.
Second, assign the result character according to the position, and finally, if there is a carry, add the carry in front of the string concatenation.
Time complexity: O (n)
Code
Java version
Class Solution {
Public String addBinary (String a, String b) {
StringBuilder ans = new StringBuilder ()
Int ca = 0
For (int I = a.length ()-1, j = b.length ()-1 political I > = 0 | j > = 0; iMurray, Jmuri -) {
Int sum = ca
Sum + = I > = 0? A.charAt (I) -'0': 0
Sum + = j > = 0? B.charAt (j) -'0': 0
Ans.append (sum 2)
Ca = sum / 2
}
Ans.append (ca = = 1? Ca: "")
Return ans.reverse () .toString ()
}
}
JavaScript version
/ * *
* @ param {string} a
* @ param {string} b
* @ return {string}
, /
Var addBinary = function (a, b) {
Let ans = ""
Let ca = 0
For (let I = a.length-1, j = b.length-1 political I > = 0 | | j > = 0; Imurmuri, Jmuri -) {
Let sum = ca
Sum + = I > = 0? ParseInt (a [I]): 0
Sum + = j > = 0? ParseInt (b [j]): 0
Ans + = sum 2
Ca = Math.floor (sum / 2)
}
Ans + = ca = = 1? Ca: ""
Return ans.split ('). Reverse (). Join (')
}
Drawing and interpretation
The above is all the contents of the article "how to solve the binary summation problem in leetcode". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!