Problem: Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
This problem can also be found in Leetcode -Add Binary
- Solution 1:
- pad 0s at front of shorter number to have them of equal length
- Iterate from the end of the numbers and add them and handle the carry
- sum will be (the sum of carry and the character's at this position) %2
- carry will be (the sum of carry and the character's at this position) /2
- Solution 2: Using bitwise operator
- sum = char of a XOR char of b XOR carry
- carry = (cahr of a & carry) XOR (char of b & carry) XOR (char of a & char of b)
No comments:
Post a Comment