-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddBinary.java
52 lines (46 loc) · 1.14 KB
/
AddBinary.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/
import java.util.*;
public class AddBinary {
public static String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int M = a.length();
int N = b.length();
int i = M-1;
int j = N-1;
int adds = 0;
while(i >= 0 || j >= 0){
int o1 = 0;
int o2 = 0;
if(i >= 0){
o1 = a.charAt(i) - '0';
i--;
}
if(j >= 0){
o2 = b.charAt(j) - '0';
j--;
}
int sum = o1+o2+adds;
sb.append(sum%2);
adds = sum/2;
}
if(adds == 1){
sb.append(1);
}
return sb.reverse().toString();
}
public static void main(String[] args) {
String p = "10111";
String s = "101";
String res = addBinary(p, s);
System.out.println("String 1: " + p);
System.out.println("String 2: " + s);
System.out.println("Result: " + res);
return;
}
}