gpt4 book ai didi

ios - Swift 将 Int[] 转换为 Int 变量

转载 作者:行者123 更新时间:2023-11-28 10:15:14 28 4
gpt4 key购买 nike

使用 Swift 3 我得到了一个从数字和反向创建的 Int 数组

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 }

现在我要

var myResult = all numbers from array in one variable

假设

myArr = [1,2,3,4]
// And i want to myResult = 1234

或者如果有任何其他方法可以只反转一个数字,我的意思是普通的整数变量?

最佳答案

将十进制数字数组组合成一个数字可以用简单的整数运算:

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?

为此您不需要数组或字符串转换:

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

关于ios - Swift 将 Int[] 转换为 Int 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274497/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com