- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAddBinary.java
More file actions
Latest commit
31 lines (27 loc) · 784 Bytes
/
Copy pathAddBinary.java
File metadata and controls
31 lines (27 loc) · 784 Bytes
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
publicclassSolution {
publicStringaddBinary(Stringa, Stringb) {
StringBufferresult = a.length()>=b.length()? newStringBuffer(a):newStringBuffer(b);
inti = a.length() - 1;
intj = b.length() - 1;
intcarry = 0;
intindex = 0;
intacurrent = 0;
intbcurrent = 0;
for(;i>=0||j>=0;i--,j--) {
acurrent = i>=0? a.charAt(i) - '0' : 0;
bcurrent = j>=0? b.charAt(j) - '0' : 0;
intcurrent = (acurrent + bcurrent + carry)%2;
carry = (acurrent + bcurrent + carry)/2;
//result = result.insert(0, current);
if(i>=j) {
result.setCharAt(i, (char)(current + '0'));
} else {
result.setCharAt(j, (char)(current + '0'));
}
}
if(carry==1) {
result.insert(0, '1');
}
returnresult.toString();
}
}