Skip to content

Commit

Permalink
[Math] Refactor solution to Add Binary
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Mar 1, 2020
1 parent 554961c commit 49820df
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions Math/AddBinary.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* Question Link: https://leetcode.com/problems/add-binary/
* Primary idea: use Carry and iterate from last to start
* Primary idea: Two pointers: use carry and iterate from last to start
*
* Note: Swift does not have a way to access a character in a string with O(1),
* thus we have to first transfer the string to a character array
Expand All @@ -10,25 +10,25 @@

class AddBinary {
func addBinary(_ a: String, _ b: String) -> String {
var sum = 0, carry = 0, res = ""
let aChars = Array(a.characters), bChars = Array(b.characters)
var i = aChars.count - 1, j = bChars.count - 1

let a = Array(a), b = Array(b)
var res = "", carry = 0, i = a.count - 1, j = b.count - 1

while i >= 0 || j >= 0 || carry > 0 {
sum = carry
var sum = carry

if i >= 0 {
sum += Int(String(aChars[i]))!
sum += Int(String(a[i]))!
i -= 1
}
if j >= 0 {
sum += Int(String(bChars[j]))!
sum += Int(String(b[j]))!
j -= 1
}

res = "\(sum % 2)" + res
carry = sum / 2
sum = sum % 2
res = String(sum) + res
}

return res
}
}

0 comments on commit 49820df

Please sign in to comment.