2

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())!

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

You asked about efficiency, as to this answer by Martin R, my guess is that is the most efficient answer

var number = 1992843
var arr = [Int]()

while number > 0 {
    arr.append(number % 10)
    number = number / 10
}

arr.sort() 
arr.reverse()

for n in arr {
    number = number * 10
    number += n
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.