var sumLeftToRight: Int = 0
var sumRightToLeft: Int = 0
var arr: [[Int]] = []
for i in 0..<arr.count {
sumLeftToRight += arr[i][i]
sumRightToLeft += arr[i][arr.count-i-1]
}
//Swift 5 Solution within a function with a bit different approach in case negative numbers in test-cases
func sumDiagonally(arr:[[Int]])-> Int{
var subn = 0
var sum1st = 0
var sum2nd = 0
for i in 0..<arr.count{
sum1st += arr[i][i]
sum2nd += arr[i][arr.count-i-1]
subn = sum1st - sum2nd
if sum1st < sum2nd{
subn = subn * -1
}
}
return subn
}
sumDiagonally(arr: [[1,2,3],
[4,5,6],
[9,8,9]])
2条答案
按热度按时间7cwmlq891#
5lhxktic2#