0

I'm attempting to get a user input number and find the sum of all the digits. I'm having issues with larger numbers, however, as they won't register under an Int64. Any idea as to what structures I could use to store the value? (I tried UInt64 and that didn't work very well with negatives, however, I'd prefer something larger than UInt64, anyways. I'm having a hard time implementing a UInt128 from Is there a number type with bigger capacity than u_long/UInt64 in Swift?)

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)")
R. R
  • 55
  • 2
  • 8
  • Have you considered using [`NSDecimalNumber`](https://developer.apple.com/documentation/foundation/nsdecimalnumber) as recommended by [this answer](https://stackoverflow.com/a/25614523/2773311) in the post you linked? It can handle numbers of the form `A*10^B` where `B` is up to 127. – Arc676 Jun 18 '17 at 02:47
  • How about just reading it as a String? – vacawama Jun 18 '17 at 02:52
  • 1
    @Arc676 - Just to set expectations accordingly, the mantissa can be 38 digits long, so if you want integer accuracy, it's a little misleading to suggest that B is up to 127. It's 38 digits max, and then you start losing accuracy. – Rob Jun 18 '17 at 03:27

1 Answers1

-2

You can use a string to perform the operation you describe. Loop through each character and convert it to an integer and add to the sum. Be careful to handle errors.

logan rakai
  • 2,519
  • 2
  • 15
  • 24
  • I've been attempting to get the user input as a string, as suggested, but I can't convert the user input string (type inout String) to an integer or a string – R. R Jun 18 '17 at 15:37
  • You will need to convert each character to an int. An example of how to loop through the characters and convert to integer is here: https://stackoverflow.com/a/30771177/5894196. Even if it is `inout` you can still use the `characters` property. – logan rakai Jun 19 '17 at 08:38