forked from yuanx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
39 lines (33 loc) · 970 Bytes
/
AddBinary.java
File metadata and controls
39 lines (33 loc) · 970 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
32
33
34
35
36
37
38
39
public class Solution {
public String addBinary(String a, String b) {
// Start typing your Java solution below
// DO NOT write main() function
int al = a.length()-1;
int bl = b.length()-1;
int carry = 0;
int temp;
String sum = "";
while(al>=0 || bl>=0){
if(al>=0 && bl>=0)
temp = (a.charAt(al)-'0') + (b.charAt(bl)-'0') + carry;
else if(al>=0)
temp = (a.charAt(al)-'0') + carry;
else
temp = (b.charAt(bl)-'0') + carry;
if(temp>=2){
carry = 1;
temp = temp-2;
}
else{
carry = 0;
}
sum = Integer.toString(temp)+sum;
al--;
bl--;
}
if(carry==1)
return "1"+sum;
else
return sum;
}
}