题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
HJ57()
func HJ57() {
while let str1 = readLine(), let str2 = readLine() {
var num1 = str1
var num2 = str2
var j = 0
var result = ""
while num1.count != num2.count {
if num1.count > num2.count {
num2.insert("0", at: num2.startIndex)
}
if num1.count < num2.count {
num1.insert("0", at: num1.startIndex)
}
}
for i in 0..<num1.count {
let idx1 = num1.index(num1.endIndex, offsetBy: -1*i - 1)
let c1 = num1[idx1]
let idx2 = num2.index(num2.endIndex, offsetBy: -1*i - 1)
let c2 = num2[idx2]
var num = Int(String(c1))! + Int(String(c2))! + j
j = 0
if num >= 10 {
j = 1
num -= 10
}
result.insert(contentsOf: String(num), at: result.startIndex)
}
if j == 1 {
result.insert("1", at: result.startIndex)
}
print(result)
}
}
func HJ57() {
while let str1 = readLine(), let str2 = readLine() {
var num1 = str1
var num2 = str2
var j = 0
var result = ""
while num1.count != num2.count {
if num1.count > num2.count {
num2.insert("0", at: num2.startIndex)
}
if num1.count < num2.count {
num1.insert("0", at: num1.startIndex)
}
}
for i in 0..<num1.count {
let idx1 = num1.index(num1.endIndex, offsetBy: -1*i - 1)
let c1 = num1[idx1]
let idx2 = num2.index(num2.endIndex, offsetBy: -1*i - 1)
let c2 = num2[idx2]
var num = Int(String(c1))! + Int(String(c2))! + j
j = 0
if num >= 10 {
j = 1
num -= 10
}
result.insert(contentsOf: String(num), at: result.startIndex)
}
if j == 1 {
result.insert("1", at: result.startIndex)
}
print(result)
}
}