1

I need to convert this 50 digit string 53503534226472524250874054075591789781264330331690 into the appropriate number type. I tried this:

let str = "53503534226472524250874054075591789781264330331690"
let num = str.toInt();         // Returns nil
let num = Int64(str.toInt());  // Errors out
Mohamad
  • 34,731
  • 32
  • 140
  • 219
  • 1
    [Hint](https://projecteuler.net/problem=13): you only need the last 10 digits. – Kevin Jan 03 '15 at 21:24
  • @Kevin, yeah, I'm aware of that, but I was just curious! Cheers! I got my math all mixed up thinking Int64 could handle 50 digits. – Mohamad Jan 03 '15 at 21:24
  • 1
    @Mohamad The width of the integer type doesn't correlate to the maximum number it can hold in that way. The maximum value of signed IntN is given by `2^(N-1)-1`, which in the case of Int64 is the number in Mondkin's answer, and in the case of Int32 is my username (in a base 10 = 2,147,483,647). – Mick MacCallum Jan 03 '15 at 21:30

1 Answers1

4

The maximimum size of an Int64 is 9,223,372,036,854,775,807 when it is signed. So you cannot convert it just like that.

You need something like the BigInt class found in other languages. Check this other question where they answer with alternatives about BigInt in Swift:

In summary, there are third-party libraries out there for arbitrary long integers. The only alternative from Apple is NSDecimalNumber but its limit is 38 digits, whereas your number has 50.

Community
  • 1
  • 1
Daniel
  • 21,933
  • 14
  • 72
  • 101