[Swift]LeetCode1073. 負二進制數相加 | Adding Two Negabinary Numbers

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/ 
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-pyleyoug-mb.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given two numbers arr1 and arr2 in base -2, return the result of adding them together.git

Each number is given in array format:  as an array of 0s and 1s, from most significant bit to least significant bit.  For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3.  A number arr in array format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.github

Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.數組

Example 1:微信

Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1] Output: [1,0,0,0,0] Explanation: arr1 represents 11, arr2 represents 5, the output represents 16. 

Note:app

  1. 1 <= arr1.length <= 1000
  2. 1 <= arr2.length <= 1000
  3. arr1 and arr2 have no leading zeros
  4. arr1[i] is 0 or 1
  5. arr2[i] is 0 or 1

給出基數爲 -2 的兩個數 arr1 和 arr2,返回兩數相加的結果。spa

數字以 數組形式 給出:數組由若干 0 和 1 組成,按最高有效位到最低有效位的順序排列。例如,arr = [1,1,0,1] 表示數字 (-2)^3 + (-2)^2 + (-2)^0 = -3。數組形式 的數字也一樣不含前導零:以 arr 爲例,這意味着要麼 arr == [0],要麼 arr[0] == 1code

返回相同表示形式的 arr1 和 arr2 相加的結果。兩數的表示形式爲:不含前導零、由若干 0 和 1 組成的數組。 orm

示例:htm

輸入:arr1 = [1,1,1,1,1], arr2 = [1,0,1]
輸出:[1,0,0,0,0]
解釋:arr1 表示 11,arr2 表示 5,輸出表示 16 。 

提示:

  1. 1 <= arr1.length <= 1000
  2. 1 <= arr2.length <= 1000
  3. arr1 和 arr2 都不含前導零
  4. arr1[i] 爲 0 或 1
  5. arr2[i] 爲 0 或 1

Runtime: 36 ms

Memory Usage: 21.4 MB
 1 class Solution {
 2     func addNegabinary(_ arr1: [Int], _ arr2: [Int]) -> [Int] {
 3         var arr1 = [Int](arr1.reversed())
 4         var arr2 = [Int](arr2.reversed())
 5         var result:[Int] = [Int]()
 6         var carry:Int = 0
 7         var i:Int = 0
 8         while(i < arr1.count || i < arr2.count || carry != 0)
 9         {
10             let num1:Int = i < arr1.count ? arr1[i] : 0
11             let num2:Int = i < arr2.count ? arr2[i] : 0
12             let x:Int =  num1 + num2 + carry
13             result.append((x + 2) % 2)
14             carry = (x - result.last!) / -2
15             i += 1
16         }
17         while(result.count > 1 && result.last! == 0)
18         {
19             result.removeLast()
20         }
21         return result.reversed()
22     }
23 }
相關文章
相關標籤/搜索