intro
计算两个字符串类型num1和num2的数字,并返回num1和num2的和。
Note:
- num1和num2的长度都小于5100
- num1和num2只包含0-9的数字
- num1和num2不包含leading zero
- 不能使用自带的库或者直接转换整形
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:The length of both num1 and num2 is < 5100.Both num1 and num2 contains only digits 0-9.Both num1 and num2 does not contain any leading zero.You must not use any built-in BigInteger library or convert the inputs to integer directly.思路
- 创建一个while循环,逆序遍历两个数组,当两个数组都遍历完且进位的sum为0的时候跳出循环,在循环中相加两个值
Code (Swift4.0)
func addStrings(_ num1: String, _ num2: String) -> String { var arr1 = [Int]() var arr2 = [Int]() var sumArr = [String]() for cha in num1.characters { arr1.append(Int(String(cha))!) } for cha in num2.characters { arr2.append(Int(String(cha))!) } var firstIndex = num1.characters.count - 1 var secondIndex = num2.characters.count - 1 var sum = 0 while (firstIndex >= 0) || (secondIndex >= 0) || sum != 0 { var firstNum = 0 if firstIndex >= 0 { firstNum = arr1[firstIndex] firstIndex -= 1 } var secondNum = 0 if secondIndex >= 0 { secondNum = arr2[secondIndex] secondIndex -= 1 } sum = sum + firstNum + secondNum sumArr.insert(String(sum%10), at: 0) sum = sum/10 } return sumArr.joined()}复制代码
result
Run Time :119ms