Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit eced7a5

Browse files
EASY/src/easy/AddBinary.java
1 parent 6cc7efc commit eced7a5

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

EASY/src/easy/AddBinary.java

+15-2
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,23 @@ public class AddBinary {
1414
//Tricks and things learned that could be learned:
1515
//1. use StringBuilder.reverse() function! Nice!
1616
//2. if a numeric number is represented/stored in String, how to get its value: use Character.getNumericValue(s.charAt(i))
17-
//3. directly adding/subtracting chars will end up working with their ASCII numbers, e.g. chars[0] = 'a', chars[1] = 'b', then chars[0] + chars[1] will become 195
17+
//3. directly adding/subtracting chars will end up working with their ASCII numbers, e.g. chars[0] = 'a', chars[1] = 'b', then chars[0] + chars[1] will become 195
18+
public String addBinary(String a, String b){
19+
int carry = 0, i = a.length()-1, j = b.length()-1;
20+
StringBuilder sb = new StringBuilder();
21+
while(i >= 0 || j >= 0){
22+
int sum = carry;
23+
if(i >= 0) sum += a.charAt(i--) - '0';
24+
if(j >= 0) sum += b.charAt(j--) - '0';
25+
sb.append(sum%2);
26+
carry = sum/2;
27+
}
28+
if(carry != 0) sb.append(carry);
29+
return sb.reverse().toString();
30+
}
1831

1932
//my original lengthy but AC'ed solution
20-
public String addBinary(String a, String b) {
33+
public String addBinary_my_original_accepted_but_lengthy_solution(String a, String b) {
2134
char[] longer = (a.length() >= b.length()) ? a.toCharArray() : b.toCharArray();
2235
char[] shorter = (a.length() < b.length()) ? a.toCharArray() : b.toCharArray();
2336
//at the maximum, the result length will be Math.max(a.length, b.length)+1;

0 commit comments

Comments
 (0)