-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAddBinary.java
66 lines (49 loc) · 1.27 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package collectionz;
//java program to add
//two binary strings
public class AddBinary {
// This function adds two
// binary strings and return
// result as a third string
static String addBinary(String a, String b)
{
// Initialize result
StringBuilder result = new StringBuilder("");
// Initialize digit sum
int s = 0;
// Traverse both strings starting
// from last characters
int i = a.length() - 1, j = b.length() - 1;
while (i >= 0 || j >= 0 || s == 1)
{
// Comput sum of last
// digits and carry
s += ((i >= 0)? a.charAt(i) - '0': 0);
s += ((j >= 0)? b.charAt(j) - '0': 0);
// If current digit sum is
// 1 or 3, add 1 to result
result.append((char)(s % 2 + '0'));
// Compute carry
s /= 2;
// Move to next digits
i--; j--;
}
// // Remove leading zeros, if any
// int start = result.length()-1;
//
// while(start >=0 && result.charAt(start) == '0') {
// start--;
// }
//
// if(start != result.length()-1) {
// result.delete(start+1,result.length());
// }
return result.reverse().toString();
}
//Driver code
public static void main(String args[])
{
String a = "1101", b="100";
System.out.print(addBinary(a, b));
}
}