[Swift]LeetCode67. 二进制求和 | Add Binary
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9697968.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1
和 0
。
示例 1:
输入: a = "11", b = "1" 输出: "100"
示例 2:
输入: a = "1010", b = "1011" 输出: "10101"
12ms
1 class Solution { 2 func addBinary(_ a: String, _ b: String) -> String { 3 let charsA = Array(a) 4 let charsB = Array(b) 5 var ans = "" 6 var m = charsA.count - 1 7 var n = charsB.count - 1 8 var carry = false 9 while m >= 0 && n >= 0 { 10 if charsA[m] == "1" && charsB[n] == "1" { 11 if carry { 12 ans = "1" + ans 13 } else { 14 ans = "0" + ans 15 } 16 carry = true 17 } else if charsA[m] == "1" || charsB[n] == "1" { 18 if carry { 19 ans = "0" + ans 20 carry = true 21 } else { 22 ans = "1" + ans 23 carry = false 24 } 25 } else { 26 if carry { 27 ans = "1" + ans 28 } else { 29 ans = "0" + ans 30 } 31 carry = false 32 } 33 m -= 1 34 n -= 1 35 } 36 while m >= 0 { 37 if charsA[m] == "1" { 38 if carry { 39 ans = "0" + ans 40 } else { 41 ans = "1" + ans 42 } 43 } else { 44 if carry { 45 ans = "1" + ans 46 } else { 47 ans = "0" + ans 48 } 49 carry = false 50 } 51 m = m - 1 52 } 53 while n >= 0 { 54 if charsB[n] == "1" { 55 if carry { 56 ans = "0" + ans 57 } else { 58 ans = "1" + ans 59 } 60 } else { 61 if carry { 62 ans = "1" + ans 63 } else { 64 ans = "0" + ans 65 } 66 carry = false 67 } 68 n -= 1 69 } 70 if carry { 71 ans = "1" + ans 72 } 73 return ans 74 } 75 }
16ms
1 class Solution { 2 func addBinary(_ a: String, _ b: String) -> String { 3 var lhs: [Character] = a.reversed() 4 var rhs: [Character] = b.reversed() 5 // zero padding 6 if lhs.count < rhs.count { 7 lhs.append(contentsOf: String(repeating: "0", count: rhs.count - lhs.count)) 8 } 9 else if rhs.count < lhs.count { 10 rhs.append(contentsOf: String(repeating: "0", count: lhs.count - rhs.count)) 11 } 12 // adding 13 let len = lhs.count 14 var step = 0 15 var result = "" 16 for i in 0..<len { 17 switch (lhs[i], rhs[i], step) { 18 case ("0", "0", 0): 19 result.append("0") 20 step = 0 21 case ("0", "0", 1): 22 fallthrough 23 case ("0", "1", 0): 24 fallthrough 25 case ("1", "0", 0): 26 result.append("1") 27 step = 0 28 case ("1", "1", 0): 29 fallthrough 30 case ("1", "0", 1): 31 fallthrough 32 case ("0", "1", 1): 33 result.append("0") 34 step = 1 35 case ("1", "1", 1): 36 result.append("1") 37 step = 1 38 default: fatalError() 39 } 40 } 41 if step == 1 { 42 result.append("1") 43 } 44 while result.last == "0" { 45 result.removeLast() 46 } 47 if result == "" { 48 result = "0" 49 } 50 return String(result.reversed()) 51 } 52 }
20ms
1 class Solution { 2 func StringToNum(_ s: String) -> Int { 3 var num = 0 4 for c in s.characters 5 { 6 var n = 0 7 if (c == "1") { 8 n = 1 9 } 10 num = num * 2 + n 11 } 12 return num 13 } 14 15 func NumToString(_ num_: Int) -> String { 16 if num_ == 0 { 17 return "0" 18 } 19 20 var num = num_ 21 var str = "" 22 while num > 0 { 23 var n = num % 2 24 num /= 2 25 var s: String 26 if n == 0 { 27 s = "0" 28 } 29 else { 30 s = "1" 31 } 32 str = s + str 33 } 34 35 return str 36 } 37 38 func StringToArr(_ s: String) -> [Int] { 39 var nums: [Int] = [Int](repeating: 0, count:s.count) 40 var idx = nums.count - 1 41 for c in s.characters 42 { 43 var n = 0 44 if (c == "1") { 45 n = 1 46 } 47 nums[idx] = n 48 idx -= 1 49 } 50 return nums 51 } 52 53 func ArrToString(_ nums: [Int]) -> String { 54 55 var str = "" 56 for i in 0...nums.count - 1 { 57 if (!(i == nums.count - 1 && nums[i] == 0)) { 58 str = String(nums[i]) + str 59 } 60 } 61 62 return str 63 } 64 65 func ArrAdd(_ a: [Int], _ b: [Int]) -> [Int] { 66 var c_cnt = max(a.count, b.count) + 1; 67 var c: [Int] = [Int](repeating: 0, count: c_cnt) 68 var up = 0 69 for i in 0...c_cnt - 1 { 70 var sum = up 71 if (i < a.count) { 72 sum += a[i] 73 } 74 if (i < b.count) { 75 sum += b[i] 76 } 77 if sum >= 2 { 78 sum -= 2 79 up = 1 80 } 81 else { 82 up = 0 83 } 84 c[i] = sum 85 } 86 return c 87 } 88 89 func addBinary(_ a: String, _ b: String) -> String { 90 var aa = StringToArr(a) 91 var bb = StringToArr(b) 92 // print(aa,bb) 93 var cc = ArrAdd(aa,bb) 94 var c = ArrToString(cc) 95 print(c) 96 97 return c 98 } 99 }
24ms
1 class Solution { 2 func addBinary(_ a: String, _ b: String) -> String { 3 var sum = 0, carry = 0, res = "" 4 let aChars = Array(a.characters), bChars = Array(b.characters) 5 var i = aChars.count - 1, j = bChars.count - 1 6 7 while i >= 0 || j >= 0 || carry > 0 { 8 sum = carry 9 if i >= 0 { 10 sum += Int(String(aChars[i]))! 11 i -= 1 12 } 13 if j >= 0 { 14 sum += Int(String(bChars[j]))! 15 j -= 1 16 } 17 carry = sum / 2 18 sum = sum % 2 19 res = String(sum) + res 20 } 21 22 return res 23 } 24 }
28ms
1 class Solution { 2 //从最低位加到最高位,当前位相加结果是%2,进位是/2, 3 //记得处理每一次的进位和最后一次的进位,最后反向输出字符。 4 func addBinary(_ a: String, _ b: String) -> String { 5 //存储字符的输出变量 6 var str:String = String() 7 //获取a的字符数量 8 var i:Int = a.count-1 9 //获取b的字符数量 10 var j:Int = b.count-1 11 //进位标志 12 var carry:Int = 0 13 while(i>=0 || j>=0) 14 { 15 var sum:Int = carry 16 if i>=0 17 { 18 //获取该索引的字符 19 var char:Character = a[a.index(a.startIndex, offsetBy: i)] 20 //将字符转换成整数 21 for code in char.unicodeScalars { 22 //字符 0 的ASCII码为48 23 sum += (Int(code.value) - 48) 24 } 25 //自减 26 i-=1 27 } 28 if j>=0 29 { 30 //获取该索引的字符 31 var char:Character = b[b.index(b.startIndex, offsetBy: j)] 32 //将字符转换成整数 33 for code in char.unicodeScalars { 34 //字符 0 的ASCII码为48 35 sum += (Int(code.value) - 48) 36 } 37 //自减 38 j-=1 39 } 40 //转换为临时字符串 41 var temp = String(sum % 2) 42 //追加到字符串末尾 43 str.append(temp[temp.startIndex]) 44 carry = sum/2 45 } 46 if carry != 0 47 { 48 //转换为临时字符串 49 var temp = String(carry) 50 //追加到字符串末尾 51 str.append(temp[temp.startIndex]) 52 } 53 //返回逆序字符串 54 return String(str.reversed()) 55 } 56 }
40ms
1 class Solution { 2 func addBinary(_ a: String, _ b: String) -> String { 3 var arr1 = [Int]() 4 for c in a { 5 arr1.append(Int(String.init(c))!) 6 } 7 var arr2 = [Int]() 8 for c in b.unicodeScalars { 9 arr2.append(Int(String.init(c))!) 10 } 11 if arr1.count > arr2.count { 12 return addBinaryWithArr(arr1, short: arr2) 13 } 14 return addBinaryWithArr(arr2, short: arr1) 15 } 16 17 func addBinaryWithArr(_ long:[Int], short:[Int]) -> String { 18 19 func toString(_ array:[Int]) -> String { 20 var str = "" 21 for num in array { 22 str += "\(num)" 23 } 24 return str 25 } 26 27 var long = long 28 var target = 0 29 var initIndex = long.count - short.count 30 var i = short.count-1 31 while i >= 0 { 32 let temp = long[initIndex + i] + short[i] + target 33 if temp > 1 { 34 /// 有进位 35 long[initIndex + i] = temp - 2 36 target = 1 37 }else{ 38 /// 无进位 39 long[initIndex + i] = temp 40 target = 0 41 } 42 i -= 1 43 } 44 45 if target == 0 { 46 return toString(long) 47 } 48 49 var j = initIndex - 1 50 while j >= 0 { 51 if long[j] == 0 { 52 long[j] = 1 53 return toString(long) 54 } 55 long[j] -= 1 56 j -= 1 57 } 58 return "1" + toString(long) 59 } 60 }
48ms
1 class Solution { 2 func addBinary(_ a: String, _ b: String) -> String { 3 4 let str = String((a.count > b.count ? a: b).reversed()) 5 let otherStr = String((a.count > b.count ? b: a).reversed()) 6 7 var needUp = false 8 var result = "" 9 10 for i in 0..<str.count { 11 12 let index = str.index(String.Index(encodedOffset: i), offsetBy: 0) 13 14 let chara = i < otherStr.count ? otherStr[otherStr.index(String.Index(encodedOffset: i), offsetBy: 0)] : "0" 15 16 if str[index] == chara && (str[index] == "1" || str[index] == "0") { 17 result.insert(needUp ? "1":"0", at: String.Index(encodedOffset: 0)) 18 needUp = str[index] == "1" 19 } else { 20 result.insert(needUp ? "0":"1", at: String.Index(encodedOffset: 0)) 21 } 22 23 if i == str.count - 1 && needUp { 24 result.insert("1", at: String.Index(encodedOffset: 0)) 25 } 26 } 27 return result 28 29 } 30 }