Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created December 26, 2012 16:58
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zac-xin/4381455 to your computer and use it in GitHub Desktop.
Save zac-xin/4381455 to your computer and use it in GitHub Desktop.
Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100".
public class Solution {
public String addBinary(String a, String b) {
// Start typing your Java solution below
// DO NOT write main() function
int la = a.length();
int lb = b.length();
int max = Math.max(la, lb);
StringBuilder sum = new StringBuilder("");
int carry = 0;
for(int i = 0; i < max; i++){
int m = getBit(a, la - i - 1);
int n = getBit(b, lb - i - 1);
int add = m + n + carry;
sum.append(add % 2);
carry = add / 2;
}
if(carry == 1)
sum.append("1");
return sum.reverse().toString();
}
public int getBit(String s, int index){
if(index < 0 || index >= s.length())
return 0;
if(s.charAt(index) == '0')
return 0;
else
return 1;
}
}
@BrandonDyer64
Copy link

Thank you for posting this. Now I can add and subtract 256 bit integers, which is necessary for nCr. Now all I have to do is get multiplication to work.

@marksunpeng
Copy link

:)

@ramdcoder
Copy link

ramdcoder commented Jul 4, 2017

This is superb!! Had been searching for long time. Thank you for sharing on how to return given two binary strings

@JMassey1
Copy link

In case anyone else meanders onto this, this can be done in what I think is an easier way by using built-in methods to the Integer class:

public class Solution{
public static String addBinary(String a, String b) {
int sum = Integer.parseInt(a,2) + Integer.parseInt(b,2);
System.out.println(sum);
System.out.println();
return Integer.toBinaryString(sum);
}
}

Integer.parseInt() is typically used to get an int from a string, however, when given a second argument, that argument acts as a radix (or a base) for it to convert from. By telling it to parse String a with radix 2, it converts the binary number given in String form, to an int in base 10 form. It does this to both the numbers being added, then adds them as ints. The new "sum" int is then returned as a binary String by running the toBinaryString method of Integer with the argument of the base 10 number you want to convert to binary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment