forked from prateekshyap/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddBinary.java
58 lines (49 loc) · 1.63 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
/*https://leetcode.com/problems/add-binary/*/
class Solution {
public String addBinary(String x, String y) {
StringBuffer result = new StringBuffer("");
StringBuffer a = new StringBuffer(x);
StringBuffer b = new StringBuffer(y);
int sum = 0, carry = 0;
//till the numbers are not exhausted
while (a.length() > 0 && b.length() > 0)
{
//extract the rightmost bits
int bit1 = a.charAt(a.length()-1) == '0' ? 0 : 1; a.delete(a.length()-1,a.length());
int bit2 = b.charAt(b.length()-1) == '0' ? 0 : 1; b.delete(b.length()-1,b.length());
/*get the sum and carry
put the formula of addition of three bits*/
sum = bit1+bit2;
sum += carry;
if (sum > 1)
{
sum -= 2;
carry = 1;
}
else
carry = 0;
result.append(sum);
}
StringBuffer rem = a.length() > 0 ? a : b;
//add the carry, if any
while (rem.length() > 0 && carry > 0)
{
int bit = rem.charAt(rem.length()-1) == '0' ? 0 : 1; rem.delete(rem.length()-1,rem.length());
sum = bit+carry;
if (sum > 1)
{
sum -= 2;
carry = 1;
}
else
{
carry = 0;
}
result.append(sum);
}
result.append(rem.reverse());
if (carry > 0)
result.append(carry);
return result.reverse().toString();
}
}