Reputation: 9
Working with Swift 3 I got an Int array created from number and Reversed
var rev:String = String(number)
var pro:String = String(rev.characters.reversed())
var myArr = rev.characters.flatMap{Int(String($0))}
myArr = myArr.sorted { $1 < $0 }
Now i want to
var myResult = all numbers from array in one variable
Let say
myArr = [1,2,3,4]
// And i want to myResult = 1234
Or if there's any other way to reverse just a number, I mean normal Integer variable?
Upvotes: 0
Views: 3562
Reputation: 72410
For that you can try like this way
let myArr = [1,2,3,4]
let myResult = myArr.map(String.init).joined()
If you want myResult as Int
then
let myResult = myArr.map(String.init).joined()
if let intResult = Int(myResult) {
print(intResult)
}
Upvotes: 3
Reputation: 2600
I'm not 100% sure what you want here. If you just want to reverse an Int then probably Martin R's solution is the best option (with simple arithmetic).
Now, if you want to sort the number and then convert it into an Int I'd recommend something like this:
let number = 1432
let string = String(String(number).characters.sorted(by: >))
let integerValue = Int(string) // Returns 4321
This will return an optional Int.
Upvotes: 0
Reputation: 539745
Combining the array of decimal digits to a number can be done with simple integer arithmetic:
let digits = [1, 2, 3, 4]
let result = digits.reduce(0, { $0 * 10 + $1 })
print(result) // 1234
Or if there's any other way to reverse just a number, I mean normal Integer variable?
You don't need an array or a string conversion for that purpose:
func reverse(_ n: Int) -> Int {
var result = 0
var n = n // A mutable copy of the given number
while n > 0 {
// Append last digit of `n` to `result`:
result = 10 * result + n % 10
// Remove last digit from `n`:
n /= 10
}
return result
}
print(reverse(12345)) // 54321
Upvotes: 5
Reputation: 3278
You can map your numbers to Strings, then concatenate them and convert the String to an Int.
if let result = Int(myArray.map{String($0)}.joined()) {
//your number
}
Upvotes: 1