Skip to content

Commit ff4c9b6

Browse files
authored
Update Add Binary.java
1 parent ee2d328 commit ff4c9b6

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

Java/Add Binary.java

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
E
2-
1519709164
3-
tags: Math, String
2+
1533603550
3+
tags: Math, String, Two Pointers
44

5-
方法一:土办法没技术把binary换成数字加起来再换成binary如果input很大那么很可能int,long都hold不住不保险
5+
#### Two pointers
6+
- Use two pointers i, j to track the 2 strings
7+
- Add when i and j are applicable. While (i >= 0 || j >= 0)
8+
- StringBuffer.insert(0, x);
9+
- handle carry
610

7-
方法二:一般方法string化为charArray,然后逐位加起最后记得处理多余的一个carry on
8-
注意: 需要从末尾加起来, 所以要用一个diff来帮助 shortArray[i-diff] 指向 shortArray的相对应index.
11+
#### wrong: convert to int
12+
- 土办法没技术把binary换成数字加起来再换成binary
13+
- 如果input很大那么很可能int,long都hold不住不保险
914

1015
```
1116
/*
@@ -23,6 +28,21 @@ Given two binary strings, return their sum (also a binary string).
2328
Tags Expand
2429
String Binary Facebook
2530
*/
31+
public class Solution {
32+
public String addBinary(String a, String b) {
33+
StringBuilder sb = new StringBuilder();
34+
int i = a.length() - 1, j = b.length() -1, carry = 0;
35+
while (i >= 0 || j >= 0) {
36+
int sum = carry;
37+
if (i >= 0) sum += a.charAt(i--) - '0';
38+
if (j >= 0) sum += b.charAt(j--) - '0';
39+
sb.insert(0, sum % 2);
40+
carry = sum / 2;
41+
}
42+
if (carry != 0) sb.insert(0, carry);
43+
return sb.toString();
44+
}
45+
}
2646

2747
/*
2848
Thoughts:
@@ -121,4 +141,4 @@ public String addBinary(String a, String b) {
121141

122142

123143

124-
```
144+
```

0 commit comments

Comments
 (0)