Created
December 26, 2012 16:58
-
-
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".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.