-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
79 lines (65 loc) · 1.73 KB
/
AddBinary.java
File metadata and controls
79 lines (65 loc) · 1.73 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package Math;
/**
* Author - archit.s
* Date - 26/09/18
* Time - 11:08 PM
*/
public class AddBinary {
public String addBinary(String a, String b) {
StringBuilder s = new StringBuilder();
int carry = 0;
int minLength;
String small, big;
if(a.length() >= b.length() ){
small = b;
big = a;
minLength = b.length();
}
else{
small = a;
big = b;
minLength = a.length();
}
for(int i=minLength-1; i>=0; i--){
int count1 = small.charAt(i) == '1' ? 1 : 0;
count1 += big.charAt(big.length() - minLength + i ) == '1' ? 1 : 0;
count1 += carry;
if(count1 == 2){
carry = 1;
s.insert(0, 0);
}
else if(count1 == 3){
carry = 1;
s.insert(0,1);
}
else{
carry = 0;
s.insert(0,count1);
}
}
int j = big.length() - small.length()-1;
while(j>=0 || carry == 1){
if(j>=0){
int count1 = carry;
count1 += big.charAt(j) == '1' ? 1 : 0;
if(count1 == 2){
carry = 1;
s.insert(0, 0);
}
else{
carry = 0;
s.insert(0,count1);
}
j--;
}
else{
s.insert(0,carry);
carry=0;
}
}
return s.toString();
}
public static void main(String[] args) {
System.out.println(new AddBinary().addBinary("100", "110010"));
}
}