Skip to content

Instantly share code, notes, and snippets.

@bittib
Last active December 9, 2016 07:06
Show Gist options
  • Save bittib/5568004 to your computer and use it in GitHub Desktop.
Save bittib/5568004 to your computer and use it in GitHub Desktop.
Add binary string
/**
* 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();
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment