Skip to content

Commit 49820df

Browse files
committed
[Math] Refactor solution to Add Binary
1 parent 554961c commit 49820df

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

Math/AddBinary.swift

+11-11
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/**
22
* 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
44
*
55
* Note: Swift does not have a way to access a character in a string with O(1),
66
* thus we have to first transfer the string to a character array
@@ -10,25 +10,25 @@
1010

1111
class AddBinary {
1212
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+
1716
while i >= 0 || j >= 0 || carry > 0 {
18-
sum = carry
17+
var sum = carry
18+
1919
if i >= 0 {
20-
sum += Int(String(aChars[i]))!
20+
sum += Int(String(a[i]))!
2121
i -= 1
2222
}
2323
if j >= 0 {
24-
sum += Int(String(bChars[j]))!
24+
sum += Int(String(b[j]))!
2525
j -= 1
2626
}
27+
28+
res = "\(sum % 2)" + res
2729
carry = sum / 2
28-
sum = sum % 2
29-
res = String(sum) + res
3030
}
31-
31+
3232
return res
3333
}
3434
}

0 commit comments

Comments
 (0)