Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find digit sum of a number in Swift

Tags:

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

like image 389
bmaliel Avatar asked Apr 06 '15 06:04

bmaliel


People also ask

How do you find the digit sum of a number?

What is digit sum? We can obtain the sum of digits by adding the digits of a number by ignoring the place values. So, for example, if we have the number 567 , we can calculate the digit sum as 5 + 6 + 7 , which will give us 18 .


2 Answers

update: Swift 5 or later We can use then new Character property wholeNumberValue:

let string = "845"
let sum = string.compactMap{$0.wholeNumberValue}.reduce(0, +)
print(sum) // 17

let integer = 845
let sumInt = String(integer).compactMap{$0.wholeNumberValue}.reduce(0, +)
print(sumInt) // 17
like image 68
Leo Dabus Avatar answered Oct 15 '22 20:10

Leo Dabus


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

Update for Swift 3/4:

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
}

print(digitSum(845)) // 17

Another implementation, just for fun:

func digitSum(_ n : Int) -> Int {
    return sequence(state: n) { (n: inout Int) -> Int? in
            defer { n /= 10 }
            return n > 0 ? n % 10 : nil
        }.reduce(0, +)
}
like image 11
Martin R Avatar answered Oct 15 '22 19:10

Martin R