Created
May 9, 2022 07:04
-
-
Save derekli66/97ebe7a5dcb9081cac2301c92ca76d9d to your computer and use it in GitHub Desktop.
LeetCode problem 67. Given two binary strings a and b, return their sum as a binary string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func addBinary(_ a: String, _ b: String) -> String { | |
var result = "" | |
let aStrArr = Array(String(a.reversed())).map{ String($0) } | |
let bStrArr = Array(String(b.reversed())).map{ String($0) } | |
var index = 0 | |
var advanced = 0 | |
while index < aStrArr.count && index < bStrArr.count { | |
if aStrArr[index] == "1" && bStrArr[index] == "1" { | |
if advanced == 1 { | |
result = result + "1" | |
advanced = 1 | |
} | |
else { | |
result = result + "0" | |
advanced = 1 | |
} | |
} | |
else if aStrArr[index] == "0" && bStrArr[index] == "0" { | |
if advanced == 1 { | |
result = result + "1" | |
advanced = 0 | |
} | |
else { | |
result = result + "0" | |
advanced = 0 | |
} | |
} | |
else { | |
if advanced == 1 { | |
result = result + "0" | |
advanced = 1 | |
} | |
else { | |
result = result + "1" | |
advanced = 0 | |
} | |
} | |
index += 1 | |
} | |
let remainingArr = (index < aStrArr.count) ? aStrArr : bStrArr | |
while advanced == 1 { | |
if index < remainingArr.count { | |
if remainingArr[index] == "0" { | |
result = result + "1" | |
advanced = 0 | |
} | |
else { | |
result = result + "0" | |
advanced = 1 | |
} | |
} | |
else { | |
result = result + "1" | |
advanced = 0 | |
} | |
index += 1 | |
} | |
while index < remainingArr.count { | |
result = result + remainingArr[index] | |
index += 1 | |
} | |
return String(result.reversed()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment