In swift 3, how to calculate each integers digits summation inside an array?
Example:
var nums = [111,222,333]
The output should be like this: [3,6,9]
which is the result of calculating: [1+1+1, 2+2+2, 3+3+3]
You could implement it as follows:
let nums = [111,222,333]
func transform(_ element: Int) -> Int {
var intsChars: [Int] = []
for char in "\(element)".characters {
intsChars.append(Int(String(char))!)
}
return intsChars.reduce(0, +)
}
let result = nums.map { transform($0) }
print(result) // [3, 6, 9]
UPDATE:
As mentioned in Martin R's answer :
func digitSum(_ n : Int) -> Int {
var n = n
var sum = 0
while n > 0 {
sum += n % 10 // Add least significant digit ...
n /= 10 // ... and remove it from the number.
}
return sum
}
you could also achieve the same output:
let result = nums.map { digitSum($0) } // [3, 6, 9]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.