Dogukan
Dogukan

Reputation: 41

How to sum of the digits of an Int

I have an Int like this

let num: Int = 123

Now I want to split it into digits like 1, 2, 3 and sum them in order to get 6.

Can you help me?

Upvotes: 1

Views: 459

Answers (4)

dfrib
dfrib

Reputation: 73236

Summing the shifted ASCII values of the character representation of your number

As an alternative to @appzYourLife:s solution, you can make use of the utf8 property of String to directly access the ASCII value of the characters in the String representation of your number

let number = 123
let foo = String(number)
    .utf8.map { Int($0) }
    .reduce(0) { $0 + $1 - 48 }

Since you know that you're going from a given number to a String, we know for certain that the characters in the String can all be represented, without loss, using utf8 encoding (even by ASCII encoding, in fact). The ASCII values of characters "0" through "9" are represented by the (UInt8, here) numbers 48 through 57, hence the shift of -48 in the reduce operation above.

Upvotes: 1

Luca Angeletti
Luca Angeletti

Reputation: 59536

Given this

let number = 123

You can

let digitsSum = String(number)
    .characters
    .flatMap { Int(String($0)) }
    .reduce(0, combine: +)

How does it work?

String(number)

The first instruction convert your Int into a String so now we have "123"

.characters

This extract an array of Characters so the output is ["1", "2", "3"]

.flatMap { Int(String($0)) }

This convert the array of Characters into an array of Int so [1, 2, 3]

.reduce(0, combine: +)

Finally each element of the array of Int is combined with the + operation. So 1 + 2 + 3.

Upvotes: 3

Greg
Greg

Reputation: 25459

You can convert number to characters and enumerate it:

let numbs = 123
let str = "\(numbs)"
let a = str.characters.reduce(0) {
    return $0 + Int("\($1)")! // Note this is an explicit unwrapped optional in production code you want to replace it with something more safety like if let
}
print("A: \(a)")

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234875

Here's how you do it.

  1. Define a variable s for the sum, initially set to 0.
  2. Define n as your number, initially set to 123.
  3. Compute n % 10 to extract the last digit. % is the modulus operator. Add that to s.
  4. Use integer arithmetic: n = n / 10 to remove that last digit.
  5. If n is zero, you're all done. Else go back to (3).

Upvotes: 5

Related Questions