大于 int64 的整数



>我正在尝试获取用户输入数字并找到所有数字的总和。但是,我在使用较大的数字时遇到了问题,因为它们不会在 Int64 下注册。关于我可以使用哪些结构来存储值的任何想法?(我尝试了 UInt64,但对负片效果不佳,但是,无论如何,我更喜欢比 UInt64 更大的东西。我很难从 Swift 中是否有容量大于 u_long/UInt64 的数字类型实现 UInt128?

import Foundation
func getInteger() -> Int64 {
var value:Int64 = 0
while true {
    //we aren't doing anything with input, so we make it a constant
    let input = readLine()
    //ensure its not nil
    if let unwrappedInput = input {
        if let unwrappedInt = Int64(unwrappedInput) {
            value = unwrappedInt
            break
        }
    }
    else { print("You entered a nil. Try again:") }
}
return value
}
print("Please enter an integer")
// Gets user input
var input = getInteger()
var arr = [Int] ()
var sum = 0
var negative = false
// If input is less than 0, makes it positive
if input < 0 {
input = (input * -1)
negative = true
}
if (input < 10) && (input >= 1) && (negative == true) {
    var remain = (-1)*(input%10)
    arr.append(Int(remain))
    input = (input/10)
}
else {
    var remain = (input%10)
    arr.append(Int(remain))
    input = (input/10)
}
}
// Adds numbers in array to find sum of digits
var i:Int = 0
var size:Int = (arr.count - 1)
while i<=size {
sum = sum + arr[i]
i = (i+1)
}
// Prints sum
print("(sum)")

您可以使用字符串来执行您描述的操作。 循环遍历每个字符并将其转换为整数并添加到总和中。 小心处理错误。

最新更新