Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
85 lines (63 loc) · 1.92 KB

File metadata and controls

85 lines (63 loc) · 1.92 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package Algorithms.string;
public class AddBinary {
public String addBinary1(String a, String b) {
if (a == null || b == null) {
return null;
}
if (a.length() == 0) {
return b;
}
if (b.length() == 0) {
return a;
}
StringBuilder sb = new StringBuilder();
int p1 = a.length() - 1;
int p2 = b.length() - 1;
int carry = 0;
while (p1 >= 0 || p2 >= 0) {
int sum = carry;
if (p1 >= 0) {
sum += (a.charAt(p1) - '0');
}
if (p2 >= 0) {
sum += (b.charAt(p2) - '0');
}
char c = sum % 2 == 1 ? '1': '0';
sb.insert(0, c);
carry = sum / 2;
p1--;
p2--;
}
if (carry == 1) {
sb.insert(0, '1');
}
return sb.toString();
}
public class Solution {
public String addBinary(String a, String b) {
// 2:34
if (a == null || b == null) {
return null;
}
int ia = a.length() - 1;
int ib = b.length() - 1;
StringBuilder sb = new StringBuilder();
int carry = 0;
while (ia >= 0 || ib >= 0 || carry == 1) {
int sum = carry;
if (ia >= 0) {
sum += a.charAt(ia) - '0';
ia--;
}
if (ib >= 0) {
sum += b.charAt(ib) - '0';
ib--;
}
carry = sum / 2;
sum %= 2;
sb.insert(0, sum);
}
return sb.toString();
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.