Skip to content

Commit a2f7993

Browse files
Add Binary : Accepted
1 parent 08ee240 commit a2f7993

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ My accepted leetcode solutions to some of the common interview problems.
183183
- [Valid Palindrome](problems/src/string/ValidPalindrome.java) (Easy)
184184
- [Simplify Path](problems/src/string/SimplifyPath.java) (Medium)
185185
- [Permutation in String](problems/src/string/PermutationInString.java) (Medium)
186+
- [Add Binary](problems/src/string/AddBinary.java) (Easy)
186187

187188
#### [Tree](problems/src/tree)
188189

‎problems/src/string/AddBinary.java‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package string;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 25/11/2017.
5+
*
6+
* Given two binary strings, return their sum (also a binary string).
7+
8+
For example,
9+
a = "11"
10+
b = "1"
11+
Return "100".
12+
*/
13+
public class AddBinary {
14+
15+
/**
16+
* Main method
17+
* @param args
18+
*/
19+
public static void main(String[] args) {
20+
System.out.println(new AddBinary().addBinary("000001010000101001", "0"));
21+
}
22+
23+
public String addBinary(String a, String b) {
24+
if(a.length() > b.length()){
25+
return calculate(a, b);
26+
} else return calculate(b, a);
27+
}
28+
29+
/**
30+
* Calculate sum
31+
* @param a length of a should always be greater or equal to b
32+
* @param b length of b should always be smaller of equal to a
33+
* @return
34+
*/
35+
private String calculate(String a, String b){
36+
int carry = 0;
37+
int d = a.length() - b.length();
38+
StringBuilder sb = new StringBuilder();
39+
for(int i = a.length() - 1; i >= 0; i --){
40+
int first = Integer.parseInt(String.valueOf(a.charAt(i)));
41+
int second = i - d >= 0 ? Integer.parseInt(String.valueOf(b.charAt(i - d))) : 0;
42+
int sum = (first + second + carry);
43+
carry = sum / 2;
44+
sb.append(sum % 2);
45+
}
46+
if(carry != 0)
47+
sb.append(carry);
48+
return sb.reverse().toString();
49+
}
50+
}

0 commit comments

Comments
 (0)