File tree 1 file changed +11
-11
lines changed
1 file changed +11
-11
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
2
* Question Link: https://leetcode.com/problems/add-binary/
3
- * Primary idea: use Carry and iterate from last to start
3
+ * Primary idea: Two pointers: use carry and iterate from last to start
4
4
*
5
5
* Note: Swift does not have a way to access a character in a string with O(1),
6
6
* thus we have to first transfer the string to a character array
10
10
11
11
class AddBinary {
12
12
func addBinary( _ a: String , _ b: String ) -> String {
13
- var sum = 0 , carry = 0 , res = " "
14
- let aChars = Array ( a. characters) , bChars = Array ( b. characters)
15
- var i = aChars. count - 1 , j = bChars. count - 1
16
-
13
+ let a = Array ( a) , b = Array ( b)
14
+ var res = " " , carry = 0 , i = a. count - 1 , j = b. count - 1
15
+
17
16
while i >= 0 || j >= 0 || carry > 0 {
18
- sum = carry
17
+ var sum = carry
18
+
19
19
if i >= 0 {
20
- sum += Int ( String ( aChars [ i] ) ) !
20
+ sum += Int ( String ( a [ i] ) ) !
21
21
i -= 1
22
22
}
23
23
if j >= 0 {
24
- sum += Int ( String ( bChars [ j] ) ) !
24
+ sum += Int ( String ( b [ j] ) ) !
25
25
j -= 1
26
26
}
27
+
28
+ res = " \( sum % 2 ) " + res
27
29
carry = sum / 2
28
- sum = sum % 2
29
- res = String ( sum) + res
30
30
}
31
-
31
+
32
32
return res
33
33
}
34
34
}
You can’t perform that action at this time.
0 commit comments