Convert a String to an Int (without Int(“1”) nor radix)

REQUIREMENTS — YOUR SOLUTION SHALL NOT USE ANY OF THE FOLLOWING APPROACHES:

Javid Poornasir
2 min readApr 29, 2022
  • Int(“123”)
  • Int(“123”, radix: 10)
  • Character.wholeNumberValue
  • NumberFormatter()

— — — — — — — — — — — — — — —

ASSUMPTIONS:

The input string that will be passed to the function you create:

  • will only contain whole numbers
  • will not contain floating-point numbers
  • will not be an empty string

— — — — — — — — — — — —

THE SOLUTIONS BELOW:

  • O(N) time
  • O(1) auxilliary space
  • Swift 5

— — — — — — — — — — — —

SOLUTION #1/3

  • L5: ‘.reversed()’ == O(1) time
  • L6: ‘base’ type == Decimal.
  • L7: We subtract 48 to get a # between 0–9

— — — — — — — — — — — —

SOLUTION #2/3

This solution is risky & will not work for every scenario. I advise against using it. I initially liked it because it appear to perform ~1 less operation per loop iteration compared to the solution above.

This solution will not return accurate results for every input string that is passed to the function; due to rounding issues that arise from the use of exponents, which are used to represent the number.

IEEE-754 can help you understand when this solution will & will not be accurate, but after all is said & done, any extra operations needed to turn this into a dependable solution will likely make this solution slower than solution #1.

— — — — — — — — — — — —

SOLUTION #3/3

The requirements say not to use this solution, but in case you want to see how it can be used:

#wholeNumberValue

— — — — — — — — — — — — — — —

RESOURCES:

--

--

Javid Poornasir
Javid Poornasir

Written by Javid Poornasir

I generally focus on iOS technologies. Here are some of my notes.

No responses yet