Reputation: 41
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
Reputation: 73236
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
Reputation: 59536
let number = 123
let digitsSum = String(number)
.characters
.flatMap { Int(String($0)) }
.reduce(0, combine: +)
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
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
Reputation: 234875
Here's how you do it.
s
for the sum, initially set to 0.n
as your number, initially set to 123.n % 10
to extract the last digit. % is the modulus operator. Add that to s
.n = n / 10
to remove that last digit.n
is zero, you're all done. Else go back to (3).Upvotes: 5