forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
53 lines (46 loc) · 1.12 KB
/
AddBinary.java
File metadata and controls
53 lines (46 loc) · 1.12 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
package String;
/**
* Author - archit.s
* Date - 07/10/18
* Time - 7:53 PM
*/
public class AddBinary {
public String addBinary(String A, String B) {
int carry = 0;
if(A.length()<B.length()){
String temp = A;
A = B;
B = temp;
}
int m = A.length()-1;
int n = B.length()-1;
StringBuilder s = new StringBuilder();
int count;
while(n>=0 || m>=0){
count = carry;
if(n>=0){
count += B.charAt(n) - '0';
n--;
}
if(m>=0){
count += A.charAt(m) - '0';
m--;
}
carry = count/2;
count = count & 1;
if(count == 1){
s.insert(0,"1");
}
else{
s.insert(0,"0");
}
}
if(carry == 1){
s.insert(0,"1");
}
return s.toString();
}
public static void main(String[] args) {
System.out.println(new AddBinary().addBinary("1110000000010110111010100100111", "101001"));
}
}