![](https://img.haomeiwen.com/i1350306/dc15147427b04858.png)
class Solution {
func addBinary(_ a: String, _ b: String) -> String {
if a.count == 0{
return b
}else if b.count == 0{
return a;
}
var result:[String] = [];
var aStrList:[Int] = []
var bStrList:[Int] = []
var count = b.count
if a.count > b.count {
count = a.count
}
for value in a.reversed() {
aStrList.append(Int(String(value))!)
}
for value in b.reversed() {
bStrList.append(Int(String(value))!)
}
var c = aStrList[0] + bStrList[0];
for i in 0..<count{
if i < aStrList.count ,i < bStrList.count{
if c > 1 {
result.append(String(c - 2))
if i == count - 1{
result.append("1");
}else{
if i + 1 > aStrList.count - 1{
c = bStrList[i + 1] + 1;
}else if i + 1 > bStrList.count - 1{
c = aStrList[i + 1] + 1;
}else{
c = aStrList[i + 1] + bStrList[i + 1] + 1;
}
}
}else{
result.append(String(c))
if i < count - 1 {
if i + 1 > aStrList.count - 1{
c = bStrList[i + 1];
}else if i + 1 > bStrList.count - 1{
c = aStrList[i + 1];
}else{
c = aStrList[i + 1] + bStrList[i + 1];
}
}
}
}else if i < aStrList.count {
if c > 1{
result.append(String(c - 2))
if i == count - 1{
result.append("1")
}else{
c = aStrList[i + 1] + 1;
}
}else{
result.append(String(c));
if i < count - 1{
c = aStrList[i + 1];
}
}
}else if i < bStrList.count{
if c > 1{
result.append(String(c - 2))
if i == count - 1{
result.append("1")
}else{
c = bStrList[i + 1] + 1;
}
}else{
result.append(String(c));
if i < count - 1{
c = bStrList[i + 1];
}
}
}
}
result = result.reversed()
return result.joined();
}
}
网友评论