bmaliel - 1 year ago 71

Swift Question

Does anyone know how to get the sum of all the digits in a number in Swift?

For example using the number

`845`

`17`

Answer Source

Here is a solution that uses simple integer arithmetic only:

```
func digitSum(var n : Int) -> Int {
var sum = 0
while n > 0 {
sum += n % 10 // Add least significant digit ...
n /= 10 // ... and remove it from the number.
}
return sum
}
println(digitSum(845)) // 17
```