Created
November 13, 2014 04:09
-
-
Save fever324/73baf4135e398909d4b8 to your computer and use it in GitHub Desktop.
Add Binary
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
/* | |
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) { | |
int longer = 0; | |
int shorter = 0; | |
boolean aIsLonger; | |
if (a.length() > b.length()) { | |
longer = a.length(); | |
shorter = b.length(); | |
aIsLonger = true; | |
} else { | |
longer = b.length(); | |
shorter = a.length(); | |
aIsLonger = false; | |
} | |
char[] result = new char[longer + 1 ]; | |
char c; | |
char d; | |
boolean carryOver = false; | |
for (int i = 0; i < longer ; i++) { | |
if (i >= shorter) { | |
if (aIsLonger) { | |
c = a.charAt(a.length() - 1 - i); | |
d = '0'; | |
} else { | |
c = '0'; | |
d = b.charAt(b.length() - 1 - i); | |
} | |
} else { | |
c = a.charAt(a.length() - 1 - i); | |
d = b.charAt(b.length() - 1 - i); | |
} | |
if (c == d) { | |
result[result.length - 1 - i] = carryOver ? '1' : '0'; | |
carryOver = c == '1'; | |
} else { | |
if((c == '1' || d == '1') && carryOver) { | |
result[result.length - 1 - i] = '0'; | |
carryOver = true; | |
} else { | |
result[result.length - 1 - i] = '1'; | |
carryOver = false; | |
} | |
} | |
} | |
String toReturn; | |
if(carryOver) { | |
result[0] = '1'; | |
toReturn = new String(result); | |
} else { | |
toReturn = new String(result); | |
toReturn = toReturn.substring(1); | |
} | |
return toReturn; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment