Thursday, February 19, 2015

LeetCode [67] Add Binary

 67. Add Binary

Easy

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 and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public String addBinary(String a, String b) {
        int n1 = a.length(), n2 = b.length();
        int i = n1-1, j = n2-1;
        StringBuilder sb = new StringBuilder();
        int c = 0;
        
        while(i>=0 || j>=0 || c>0){
            int s = c;
            if(i>=0) s += a.charAt(i)-'0';
            if(j>=0) s += b.charAt(j)-'0';
            c = s/2;
            s = s%2;
            sb.append((char)(s+'0'));
            i--;
            j--;
        }
        
        return sb.reverse().toString();
    }
}

No comments:

Post a Comment