1
1
E
2
- 1519709164
3
- tags : Math , String
2
+ 1533603550
3
+ tags : Math , String , Two Pointers
4
4
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
6
10
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不住 。不保险 。
9
14
10
15
```
11
16
/*
@@ -23,6 +28,21 @@ Given two binary strings, return their sum (also a binary string).
23
28
Tags Expand
24
29
String Binary Facebook
25
30
*/
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
+ }
26
46
27
47
/*
28
48
Thoughts:
@@ -121,4 +141,4 @@ public String addBinary(String a, String b) {
121
141
122
142
123
143
124
- ```
144
+ ```
0 commit comments