bmaliel bmaliel - 4 months ago 20
Swift Question

Find digit sum of a number in Swift

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

For example using the number

845
would result in
17

Answer

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