Skip to content

Instantly share code, notes, and snippets.

@manishsat
Forked from bittib/AddBinary.java
Created December 9, 2016 07:06
Show Gist options
  • Select an option

  • Save manishsat/c934e04427369437d01faaf6aa380a2c to your computer and use it in GitHub Desktop.

Select an option

Save manishsat/c934e04427369437d01faaf6aa380a2c to your computer and use it in GitHub Desktop.

Revisions

  1. @bittib bittib revised this gist May 13, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions AddBinary.java
    Original file line number Diff line number Diff line change
    @@ -16,9 +16,9 @@ public String addBinary(String a, String b) {
    while (i >= 0 || j >= 0 || carry > 0){
    int ck = carry;
    if (i >= 0)
    ck += a.charAt(i) - '0';
    ck += a.charAt(i--) - '0';
    if (j >= 0)
    ck += b.charAt(j) - '0';
    ck += b.charAt(j--) - '0';
    if (ck > 1){
    ck -= 2;
    carry = 1;
  2. @bittib bittib revised this gist May 13, 2013. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions AddBinary.java
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,12 @@
    /**
    * LeetCode Add Binary Probem
    Given two binary strings, return their sum (also a binary string).
    For example,
    a = "11"
    b = "1"
    Return "100".
    */
    public String addBinary(String a, String b) {
    int n = a.length(), m = b.length();
  3. @bittib bittib created this gist May 13, 2013.
    26 changes: 26 additions & 0 deletions AddBinary.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    /**
    * LeetCode Add Binary Probem
    */
    public String addBinary(String a, String b) {
    int n = a.length(), m = b.length();
    char[] chs = new char[Math.max(n, m) + 1];

    int i = n-1, j = m-1, k = chs.length-1, carry = 0;
    while (i >= 0 || j >= 0 || carry > 0){
    int ck = carry;
    if (i >= 0)
    ck += a.charAt(i) - '0';
    if (j >= 0)
    ck += b.charAt(j) - '0';
    if (ck > 1){
    ck -= 2;
    carry = 1;
    }else
    carry = 0;
    chs[k--] = (char)('0' + ck);
    }
    k++;
    while (k < chs.length-1 && chs[k] == '0')
    k++;
    return new String(chs, k, chs.length - k);
    }