I am trying to convert an Int array to an Int number. What I am now
doing is converting it to a String array and then use the joined() function. Is there a more efficient way to do this?
Example:
let sortedIntArray = String(number).characters.map{Int(String($0)) ?? 0}.sorted(by: { $0 > $1 })
let desOrder = Int(sortedIntArray.map{String($0)}.joined())!
In your case, sortedIntArray is an array of single-digit numbers,
and then you can combine them without any conversion to strings:
let sortedIntArray = [4, 2, 1]
let result = sortedIntArray.reduce(0) { 10 * $0 + $1 }
print(result) // 421
Combined with the dfri's elegant solution to split the number into an integer array:
let number = 1439
let descDigits = sequence(state: number, next: { (num: inout Int) -> Int? in
return num > 0 ? (num % 10, num /= 10).0 : nil
}).sorted(by: >)
print(descDigits) // [9, 4, 3, 1]
let descNumber = descDigits.reduce(0) { 10 * $0 + $1 }
print(descNumber) // 9431
Use the reduce method instead of map and joined
let desOrder = Int(sortedIntArray.reduce("") { $0 + String($1) })
reduce(intialResult: Result, (Result, Any) throws -> Result) rethrows
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With