Add Binary Problem LeetCode

Given two binary strings, return their sum (also a binary string).

Example
  • a = "11"
  • b = "1"
  • Return "100".
 This problem can also be found in Leetcode -Add Binary A collection of hundreds of interview questions and solutions are available in our blog at Interview Question

  1.  Solution 1:
    1. pad 0s at front of shorter number to have them of equal length
    2.  Iterate from the end of the numbers and add them and handle the carry
    3. sum will be (the sum of carry and the character's at this position) %2
    4.  carry will be (the sum of carry and the character's at this position) /2
  2.  Solution 2: Using bitwise operator
    1. sum = char of a XOR char of b XOR carry
    2.  carry = (cahr of a & carry) XOR (char of b & carry) XOR (char of a & char of b)

Solution

No comments:

Post a Comment