在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given two numbers Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, Return the result of adding Example 1: Input: arr1 = [1,0,1]
Output: [1,0,0,0,0]
Explanation: arr1 represents 11, arr2 represents 5, the output represents 16.
Note:
给出基数为 -2 的两个数 数字以 数组形式 给出:数组由若干 0 和 1 组成,按最高有效位到最低有效位的顺序排列。例如, 返回相同表示形式的 示例: 输入:arr1 = [1,1,1,1,1], arr2 = [1,0,1] 输出:[1,0,0,0,0] 解释:arr1 表示 11,arr2 表示 5,输出表示 16 。 提示:
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 }
|
请发表评论