整数大于Int64

时间:2017-06-18 02:44:39

标签: ios swift xcode uint64

我正在尝试获取用户输入数字并找到所有数字的总和。但是,我遇到了更大数字的问题,因为它们不会在Int64下注册。知道我可以用什么结构来存储价值吗? (我尝试了UInt64,但是对于负面效果并不是很好,但是,我更喜欢比UInt64更大的东西。反正。我很难从Is there a number type with bigger capacity than u_long/UInt64 in Swift?实现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)")

1 个答案:

答案 0 :(得分:0)

您可以使用字符串来执行您描述的操作。 Loop through each character并将其转换为整数并添加到总和中。小心处理错误。